how to format long if conditions

Ben Finney ben+python at benfinney.id.au
Sat Aug 27 08:04:19 EDT 2011


Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:

> I believe that PEP 8 now

Specifically the “Indentation” section contains::

    When using a hanging indent the following considerations should be
    applied; there should be no arguments on the first line and further
    indentation should be used to clearly distinguish itself as a
    continuation line.

> suggests something like this:
>
>         if (
>                 isinstance(left, PyCompare) and isinstance(right, PyCompare)
>                 and left.complist[-1] is right.complist[0]):
>             )
>             py_and = PyCompare(left.complist + right.complist[1:]
>         else:
>             py_and = PyBooleanAnd(left, right)

That gives a SyntaxError. I think you mean one of these possible PEP 8
compliant forms::

    if (
            isinstance(left, PyCompare) and isinstance(right, PyCompare)
            and left.complist[-1] is right.complist[0]):
        py_and = PyCompare(left.complist + right.complist[1:]
    else:
        py_and = PyBooleanAnd(left, right)

or maybe::

    if (
            isinstance(left, PyCompare) and isinstance(right, PyCompare)
            and left.complist[-1] is right.complist[0]
            ):
        py_and = PyCompare(left.complist + right.complist[1:]
    else:
        py_and = PyBooleanAnd(left, right)

> I consider that hideous

I think both of those (once modified to conform to both the Python
syntax and the PEP 8 guidelines) look clear and readable.

I mildy prefer the first for being a little more elegant, but the second
is slightly better for maintainability and reducing diff noise. Either
one makes me happy.

> and would prefer to write this:
>
>         if (isinstance(left, PyCompare) and isinstance(right, PyCompare)
>             and left.complist[-1] is right.complist[0]):
>             py_and = PyCompare(left.complist + right.complist[1:]
>         else:
>             py_and = PyBooleanAnd(left, right)

That one keeps tripping me up because the indentation doesn't make clear
where subordinate clauses begin and end. The (current) PEP 8 rules are
much better for readability in my eyes.


Having said that, I'm only a recent convert to the current PEP 8 style
for indentation of condition clauses. It took several heated arguments
with colleagues before I was able to admit the superiority of clear
indentation :-)

-- 
 \      “I am too firm in my consciousness of the marvelous to be ever |
  `\       fascinated by the mere supernatural …” —Joseph Conrad, _The |
_o__)                                                     Shadow-Line_ |
Ben Finney



More information about the Python-list mailing list