Naftali Harris

Style for Python Multiline If-Statements

April 10, 2017

PEP 8 gives a number of acceptable ways of handling multiple line if-statements in Python. But to be honest, most of the styles I've seen--even those that conform with the PEP--seem ugly and hard to read for me. So here's my favorite style:

if (
    some_super_long_condition
    and some_other_condition
    and one_more_condition
):
    do_something_awesome()
    do_something_else_awesome()
    etc()
else:
    dont_do_anything_awesome()

What are some of the "advantages" of this style? Well, for one, I like how the code for the condition, True, and False branches all line up. It looks visually pleasant, (at least to me). And I also like how adding or removing clauses from the condition will only change a single line, (unless you remove the first condition, "some_super_long_condition"). This makes it easy to see the history with git-blame. Finally, I like how this style lends itself very naturally to refactoring the condition into its own variable, like so:

be_awesome = (
    some_super_long_condition
    and some_other_condition
    and one_more_condition
)
if be_awesome:
    ...

There's something satisfying to me about having a unified style regardless of whether or not you use an intermediate variable for your condition. And once again, if you change between these two formats, none of the actual lines with conditions changed here, making git-blame that much more useful.

You might also enjoy...