Search code examples
pythonpython-3.8python-assignment-expression

assignment expressions with conditional expression


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))

Solution

  • 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)
    )