Code-style for indention of multi-line 'if' statement?

ThiefMaster picture ThiefMaster · Feb 25, 2011 · Viewed 34.7k times · Source

When indenting long if conditions, you usually do something like this (actually, PyDev indents like that):

if (collResv.repeatability is None or
    collResv.somethingElse):
    collResv.rejected = True
    collResv.rejectCompletely()

However, this puts the block started by the if statement on the same indentation level as the last part of the if condition which makes it very ugly/hard to read in my opinion as you don't immediately see where the block starts.

Some other styles I thought about:

if (collResv.repeatability is None or
        collResv.somethingElse):
    collResv.rejected = True
    collResv.rejectCompletely()

This looks pretty inconsistent as the second line is indented much more than the first line but it's readable.

if (collResv.repeatability is None or
  collResv.somethingElse):
    collResv.rejected = True
    collResv.rejectCompletely()

This is also more readable than the first example, but the indentation is not a multiple of 4 anymore and besides that it looks wrong as the second line has less indentation than the beginning of the condition in the first line.


So, my main question is: Is there a suggested indentation style for cases like that which do not require overly-long lines (i.e. a single-line condition)? If not, what do you prefer for cases like that?

Answer

Oben Sonne picture Oben Sonne · Feb 25, 2011

Often I work around this problem by calculating the condition in an own statement:

condition = (collResv.repeatability is None or
             collResv.somethingElse)
if condition:
    collResv.rejected = True
    collResv.rejectCompletely()

Though, for a still relatively short condition as in your specific example I'd go for nosklo's solution - the extra statement used here is more suited for even longer conditional expressions.