Reputation: 21426
x = 'foo' if x == 'bar' else x
now this would be equal to :
x = 'foo' if x == 'bar'
but this returns "invalid syntax" error. Is there a reason why this works like it does or what's the reason behind the design decision? Because it's how multi-line if function is (functions like example #2):
if x == 'foo':
x = 'bar'
and it works perfectly fine.
Upvotes: 4
Views: 917
Reputation: 4129
It's because it's not a statement but an expression. It must evaluate to something, so you can't exclude the else condition. Also, since it's an expression, you can't (really, you shouldn't) do anything that would mutate state.
More info here: https://docs.python.org/2/reference/expressions.html#conditional-expressions
Of course, something like this is entirely possible:
class C(object):
def foo(self):
self.y = 1
return 'foo'
c = C()
c.foo() if True else 'bar'
print c.y
# Prints '1'
...so mutating state in a ternary expression is actually not prohibited; it's just not recommended.
Upvotes: 7
Reputation: 526583
To the Python interpreter, this line of code...
x = 'foo' if x == 'bar' else x
isn't interpreted like this...
(x = 'foo') if x == 'bar' else (x = x)
but rather is interpreted like this:
x = ('foo' if x == 'bar' else x)
This is because the ternary x if cond else y
operator in Python is an expression rather than a statement - it can be used anywhere you'd specify a value.
Thus, you can also use it, for example, in cases where you're not doing assignment:
print("hi" if x == 'bar' else "bye")
Because it's an expression, it always needs to be able to resolve to some value, so that the value can be used in whatever context the expression is being used.
Upvotes: 10
Reputation: 97571
The python mantra says there should be only one way to do things. We already have:
if x == 'foo': x = 'bar'
Why would we want:
x = 'bar' if x == 'foo'
Upvotes: 3