How to make a line break on the Python ternary operator?

nedim picture nedim · Mar 6, 2015 · Viewed 16.5k times · Source

Sometimes a line containing a ternary operator in Python gets too long:

answer = 'Ten for that? You must be mad!' if does_not_haggle(brian) else "It's worth ten if it's worth a shekel."

Is there a recommended way to make a line break at 79 characters with a ternary operator? I did not find it in PEP 8.

Answer

Martijn Pieters picture Martijn Pieters · Mar 6, 2015

You can always extend a logical line across multiple physical lines with parentheses:

answer = (
    'Ten for that? You must be mad!' if does_not_haggle(brian)
    else "It's worth ten if it's worth a shekel.")

This is called implicit line joining.

The above uses the PEP8 everything-indented-one-step-more style (called a hanging indent). You can also indent extra lines to match the opening parenthesis:

answer = ('Ten for that? You must be mad!' if does_not_haggle(brian)
          else "It's worth ten if it's worth a shekel.")

but this leaves you hitting the 80-column maximum all the faster.

Where precisely you put the if and else portions is up to you; I used my personal preference above, but there is no specific style for the operator that anyone agrees on, yet.