Code formatting question: conditional expression

Ben Finney ben+python at benfinney.id.au
Tue Aug 18 17:19:39 EDT 2009


John Posner <jjposner at optimum.net> writes:

> Is there any consensus on how to format a conditional expression that
> is too long for one line? How about this:
>
>  excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True)
>               if total > P.BASE else
>               None)
>
> The above format separates the values from the if-then-else machinery.
> Too many lines?

Too much indentation, and worse, indentation that changes based on a
distractingly irrelevant quantity: the length of the first line. I
prefer::

    excessblk = (
        Block(total - P.BASE, srccol, carry_button_suppress=True)
        if total > P.BASE else None)

> Would it be better to line up "if" and "else" vertically? ...

If the expression assigned in the ‘else’ branch were also quite long,
I'd say yes::

    excessblk = (
        Block(total - P.BASE, srccol, carry_button_suppress=True)
        if total > P.BASE
        else Block(total, srccol, carry_button_suppress=False))

-- 
 \          “Friendship is born at that moment when one person says to |
  `\    another, ‘What! You too? I thought I was the only one!’” —C.S. |
_o__)                                                            Lewis |
Ben Finney



More information about the Python-list mailing list