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
eval
uated, statements areexec
uted. 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
but you could also do
In the first example, you assign 15 to the variable
i
, and this new value ofi
is then evaluated by theif
.Even worse are increment/decrement operators. What is the difference between
and
?
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 ifi
was1
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.