Saturday, 2 September 2017

python - Styling multi-line conditions in 'if' statements?



Sometimes I break long conditions in ifs onto several lines. The most obvious way to do this is:



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



Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.



For the moment I'm using:



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



But this isn't very pretty. :-)



Can you recommend an alternative way?


Answer



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_something
if (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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...