Sometimes I break long conditions in if
s 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?
I'm surprised not to see my preferred solution,
Since
and
is a keyword, it gets highlighted by my editor, and looks sufficiently different from the do_something below it.Someone has to champion use of vertical whitespace here! :)
This makes each condition clearly visible. It also allows cleaner expression of more complex conditions:
Yes, we're trading off a bit of vertical real estate for clarity. Well worth it IMO.
You could split it into two lines
Or even add on one condition at a time. That way, at least it separates the clutter from the
if
.This doesn't improve so much but...
What if we only insert an additional blank line between the condition and the body and do the rest in the canonical way?
p.s. I always use tabs, not spaces; I cannot fine-tune...
Just a few other random ideas for completeness's sake. If they work for you, use them. Otherwise, you're probably better off trying something else.
You could also do this with a dictionary:
This option is more complicated, but you may also find it useful:
Dunno if that works for you, but it's another option to consider. Here's one more way:
The last two I haven't tested, but the concepts should be enough to get you going if that's what you want to go with.
(And for the record, if this is just a one time thing, you're probably just better off using the method you presented at first. If you're doing the comparison in lots of places, these methods may enhance readability enough to make you not feel so bad about the fact that they are kind of hacky.)