Python Ternary Conditional – Using Statements on Either Side

pythonsyntaxternary

Why is it prohibited to use statements on either side of python's ternary conditional? I can't see any obvious reason how a few of the following naive syntax examples could be ambiguous or broken – but I'm sure there must be a good reason why it's disallowed!

>>> x, y = 0, 0
>>> (x += 1) if random.choice([0, 1]) else (y += 1)
        ^
SyntaxError: invalid syntax

>>> (x if random.choice([0, 1]) else y) += 1
SyntaxError: can't assign to conditional expression


>>> print 'hello world' if random.choice([0, 1]) else raise StandardError()
  File "<stdin>", line 1
    print 'hello world' if random.choice([0, 1]) else raise StandardError()
                                                          ^
SyntaxError: invalid syntax

Can you give an example where allowing a statement to be used in a ternary could be dangerous or ill-defined?

Best Answer

Expressions are evaluated, statements are executed. This is something completely different.

Python developers have decided to strictly separate between expressions and statements . This will make you "fail early" instead of ending up with an error that is hard to debug.

In other languages, like C(++), you can do things like

if (i=15) {...}

but you could also do

if (i==15) {...}

In the first example, you assign 15 to the variable i, and this new value of i is then evaluated by the if.

Even worse are increment/decrement operators. What is the difference between

if (i--) {...}

and

if (--i) {...}

?

For the first example, the value of i is evaluated, then it is incremented. For the second example, the order is the other way around, so if i was 1 before, the result is different.

In Python, such things are prohibited by the syntax, due to the experience gathered with such concepts in other languages.

I'm not quite sure if this completely answers your question, but I hope I at least could give some insight into the pythonic approach.

Related Question