Search code examples
pythonnested-statement

Nesting the ternary operator in Python


In the Zen of Python, Tim Peters states that Flat is better than nested.. If I have understood that correctly, then in Python, this:

<statement-1> if <condition> else <statement-2>

is generally preferred over this:

if <condition>:
    <statement-1>
else:
    <statement-2>

However, in other languages, I have been told not to nest the ternary operator, and the instead use the traditional if...else. My question, then, is should I use this:

(<statement-1> if <condition-1> else <statement-2>) if <condition-2> else <statement-3>

or

if <condition-2>:
    if <condition-1>:
        <statement-1>
    else:
        <statement-2>
else:
    <statement-3>

? Particularly if the statements and conditions are long, and the first line would need splitting?


Solution

  • "Flat is better than nested" is about module organization and perhaps data structures, not your source code. The standard library, for example, mostly exists as top-level modules with very little nesting.

    Don't nest the ternary operator, or even use it at all if you can avoid it. Complex is better than complicated. :)