10

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?

LazySloth13
  • 2,369
  • 8
  • 28
  • 37

3 Answers3

28

Your first example (the horrid one-liner) is nested too. Horizontally nested. Your second example is vertically nested. They're both nested.

So which is better? The second one! Why? Because "sparse is better than dense" breaks the tie.

It's easy when you're Tim Peters - LOL ;-)

Tim Peters
  • 67,464
  • 13
  • 126
  • 132
2

"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. :)

Eevee
  • 47,412
  • 11
  • 95
  • 127
  • 5
    I don't agree with the 'or even use it at all if you can avoid it' - it's a lovely piece of syntax if used correctly. – Ben Oct 28 '13 at 23:15
  • @Ben in my experience: if the surrounding code is simple, the ternary doesn't buy you much. if the surrounding code is complicated, ternary will make it worse. – Eevee Oct 28 '13 at 23:16
  • 1
    I like to use it in return statements where the value returned depends on a simple test. – Ben Oct 28 '13 at 23:17
  • 4
    ternary operator is part and parcel of fp. please do use. – juanchito May 10 '17 at 16:01
2

To my understanding, this is "flater":

if <condition_2> and <condition_1>:
  <statement_1>
elif <condition_2>:
  <statement_2>
else:
  <statement_3>

The order of the conditions to check is important, e.g. should you put <condition_2> only as the first order of checking, then <statement_1> will never be called.

Fong Kah Chun
  • 789
  • 6
  • 6
  • Even more so if the conditional involved more levels of nesting; I think this is one of the most reasonable options. – Anakhand Jun 22 '20 at 08:34