0

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))
Alexander McFarlane
  • 8,800
  • 7
  • 47
  • 91

2 Answers2

2

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)
)
keepAlive
  • 4,938
  • 4
  • 20
  • 36
1
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!

Eeshaan
  • 1,158
  • 3
  • 16
  • thanks - I previously thought assignment was done first; then the rest of the expression – Alexander McFarlane Oct 16 '20 at 14:49
  • great! although I was wondering why you would want to convert to int if it's already an int?! – Eeshaan Oct 16 '20 at 15:00
  • perhaps you were looking for `if not y.is_integer()`? – Eeshaan Oct 16 '20 at 15:03
  • Maybe because `is_integer` does the same kind of job as `isdigit`, which checks implicite types of strings, e.g. `int('2') if '2'.isdigit() else '2'`. – keepAlive Oct 16 '20 at 15:07
  • @keepAlive oh yeah, that could be! – Eeshaan Oct 16 '20 at 15:11
  • @AlexanderMcFarlane would be great, if you can upvote / accept one our answers. If none of the answers are helpful, kindly tell us what exactly you're looking for – Eeshaan Oct 16 '20 at 15:15
  • both are answer two parts of the question tbh - sorry I had to run into meetings. Yours pointed out that misnomer that the assignment wasn't evaluated upfront, whereas https://stackoverflow.com/a/64391064/4013571 shows how to correctly assign it - as a result I upvoted them both, many thanks for your help – Alexander McFarlane Oct 16 '20 at 15:50