This has nothing to do with conditional expressions1. Python programs are made up of statements. Most parts of most statements are expressions. Expressions only contain other expressions.
y += 1
is a statement, and isn't allowed where an expression is expected. The ternary conditional as a whole is an expression, and each of the 3 parts of it are expressions. There's no more reason to allow (x += 1) if random.choice([0, 1]) else (y += 1)
than there is to allow any of the following monstrosities:
x = (y += 1)
def foo(x=(x += 1)):
print x
print [x += 1, x *= 10]
Expressions are things that can be evaluated to some value; statements are things that don't have a value. If you allow statements as the "when true" or "when false" operands of a conditional expression, then why not allow any statement in any expression? After all, it would complicate the grammar to special case it so that the conditional expression was the only kind of expression that could contain a statement.
x = y + pass
[return True, import sys]
None of these make any sense. Neither does (x += 1) if random.choice([0, 1]) else (y += 1)
, because the whole point of conditional expressions is to be expressions. So it would more realistically appear in a statement, such as:
z = (x += 1) if random.choice([0, 1]) else (y += 1)
You could conceivable rule that the "value" of x += 1
is the value of x
(either before or after 1 has been added), as C does. But it makes the language considerably more complicated. And that still doesn't solve the problem of:
z = pass if (import sys) else (while False: print 17)
What is the value of pass
? Of import sys
? Of a while loop?
To make this work you would have to separate out "statements" as a class of things that exists in the grammar of Python into "expressiony statements" and "normal statements", or invent some arbitrary rules about what the value of certain kinds of statement are. Probably both.
The simple fact is, if you're trying to write this as a single statement:
(x += 1) if random.choice([0, 1]) else (y += 1)
Then Python already has the syntax for expressing this idea, and it is this:
if random.choice([0, 1]):
x += 1
else:
y += 1
There's no need to introduce the complexities to the language (and to readability) of putting statements as components of expressions just so you can obfuscate if
statements by writing them as conditional expressions (whose value is ignored).
1 Call it a "ternary conditional" if you must, but "ternary" or "ternary operator" is just plain silly. That it has 3 operands is hardly the most important thing about it; that's like calling +
"binary operator".