pythoncoding-styleindentationcode-readability

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


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?


Solution

  • This is an indirect answer--not answering the style question directly, but it's the practical answer in general, so it's worth mentioning.

    I find it extremely rare to need to write multi-line conditionals. There are two factors to this:

    Grepping through my recent projects, around 12kloc, there's only one conditional long enough that it needed to be wrapped; the issue simply very rarely arises. If you do need to do this, then as nosklo says, indent it separately--as you noticed, indenting it to the same level as the block beneath it is confusing and hard to read.