Styling multi-line conditions in 'if' statements? [closed] Styling multi-line conditions in 'if' statements? [closed] python python

Styling multi-line conditions in 'if' statements? [closed]


You don't need to use 4 spaces on your second conditional line. Maybe use:

if (cond1 == 'val1' and cond2 == 'val2' and        cond3 == 'val3' and cond4 == 'val4'):    do_something

Also, don't forget the whitespace is more flexible than you might think:

if (          cond1 == 'val1' and cond2 == 'val2' and        cond3 == 'val3' and cond4 == 'val4'   ):    do_somethingif    (cond1 == 'val1' and cond2 == 'val2' and        cond3 == 'val3' and cond4 == 'val4'):    do_something

Both of those are fairly ugly though.

Maybe lose the brackets (the Style Guide discourages this though)?

if cond1 == 'val1' and cond2 == 'val2' and \   cond3 == 'val3' and cond4 == 'val4':    do_something

This at least gives you some differentiation.

Or even:

if cond1 == 'val1' and cond2 == 'val2' and \                       cond3 == 'val3' and \                       cond4 == 'val4':    do_something

I think I prefer:

if cond1 == 'val1' and \   cond2 == 'val2' and \   cond3 == 'val3' and \   cond4 == 'val4':    do_something

Here's the Style Guide, which (since 2010) recommends using brackets.


I've resorted to the following in the degenerate case where it's simply AND's or OR's.

if all( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):if any( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):

It shaves a few characters and makes it clear that there's no subtlety to the condition.


Someone has to champion use of vertical whitespace here! :)

if (     cond1 == val1     and cond2 == val2     and cond3 == val3   ):    do_stuff()

This makes each condition clearly visible. It also allows cleaner expression of more complex conditions:

if (    cond1 == val1     or         (     cond2_1 == val2_1          and cond2_2 >= val2_2          and cond2_3 != bad2_3        )   ):    do_more_stuff()

Yes, we're trading off a bit of vertical real estate for clarity. Well worth it IMO.


matomo