assignment expressions with conditional expression

1.1k Views Asked by At

The following snippet

def expensive_function(x):
    return x

x = 10.5
(int(y) if y.is_integer() else y := expensive_function(x))

raises

SyntaxError: cannot use assignment expressions with conditional expression 

Can assignment expressions not be used in this way?

If not, what is wrong with my assumption: I was under the impression the idea is to pre-assign a dummy value to an expensive operation in a single expression.


To clarify the idea is asking if assignment operations can be used to simplify by assigning expensive_function(x) to a dummy variable

def expensive_function(x):
    return x

x = 10.5
(int(expensive_function(x))
 if expensive_function(x).is_integer()
 else expensive_function(x))
2

There are 2 best solutions below

5
On BEST ANSWER

What about

z = int(y) if (y := expensive_function(x)).is_integer() else y

?


Actually, in a if cond else b, there are two conditional expressions: the a- and the b-members. But the middle member, i.e. the cond one is not conditional: it is always evaluated, explaining why using an assigment operator there raises no error.


A prior-to-3.8 approach (i.e. with no Walrus Operator) can be

z = (
    lambda y: int(y) if y.is_integer() else y
)(
    expensive_function(x)
)
7
On
int(y) if y.is_integer() else y := expensive_function(x)

is equivalent to

def foo(x):
  if y.is_integer():
     return int(y)
  else:
     y = expensive_function(x)
     return y
foo(x)

Now you can see where the problem is. y isn't defined!