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 prefer this style when I have a terribly large if-condition:
Plain and simple, also passes pep8 checks:
In recent times I have been preferring the
all
andany
functions, since I rarely mix And and Or comparisons this works well, and has the additional advantage of Failing Early with generators comprehension:Just remember to pass in a single iterable! Passing in N-arguments is not correct.
Note:
any
is like manyor
comparisons,all
is like manyand
comparisons.This combines nicely with generator comprehensions, for example:
More on: generator comprehension
Here's what I do, remember that "all" and "any" accepts an iterable, so I just put a long condition in a list and let "all" do the work.
Personally, I like to add meaning to long if-statements. I would have to search through code to find an appropriate example, but here's the first example that comes to mind: let's say I happen to run into some quirky logic where I want to display a certain page depending on many variables.
English: "If the logged-in user is NOT an administrator teacher, but is just a regular teacher, and is not a student themselves..."
Sure this might look fine, but reading those if statements is a lot of work. How about we assign the logic to label that makes sense. The "label" is actually the variable name:
This may seem silly, but you might have yet another condition where you ONLY want to display another item if, and only if, you're displaying the teacher panel OR if the user has access to that other specific panel by default:
Try writing the above condition without using variables to store and label your logic, and not only do you end up with a very messy, hard-to-read logical statement, but you also just repeated yourself. While there are reasonable exceptions, remember: Don't Repeat Yourself (DRY).
or if this is clearer:
There is no reason indent should be a multiple of 4 in this case, e.g. see "Aligned with opening delimiter":
http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Indentation#Indentation
I guess something like this is the most readable option: