2

Why can I use something like

import numpy as np

print( (g := np.arange(256)**2) / np.max(g) )

but the following fails?

foo = list(range(256))
for i in range( (l := len(foo)) // 16 + 0 if l%16 == 0 else 1 ):
    print(i)
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    for i in range( (l := len(foo)) // 16 + 0 if l%16 == 0 else 1 ):
NameError: name 'l' is not defined
1
  • You have not defined l. First l%16 == 0 is evaluated which fails. Commented Apr 9, 2020 at 16:10

1 Answer 1

3

In an argument list, expressions are evaluated from left to right, so in:

plt.plot( range( len( (Y := foo) )), Y )

the first argument range( len( (Y := foo) )) is evaluated before the second argument Y, and therefore Y is defined with foo before Y is referenced as a second argument.

However, in a conditional expression, the expression in the if clause is evaluated before either of the outputting expressions is evaluated, so in:

(l := len(foo)) // 16 + 0 if l%16 == 0 else 1

l%16 == 0 is evaluated first, and since l isn't yet defined at that point, it raises the said NameError.

You can instead define l in the if clause first if that is indeed the logic you want:

for i in range( l // 16 + 0 if (l := len(foo))%16 == 0 else 1 ):
Sign up to request clarification or add additional context in comments.

4 Comments

So, the Assignment Expressions are always evaluated first? Is there a sane way to alter the evaluation order or to make this work?
No, my point is exactly the opposite. Assignment expressions don't get evaluated first, but rather follows the regular order of operator precedence. There is no way to alter the operator precedence since it is part of the definition of Python syntax.
By the way, is my suggestion of for i in range( l // 16 + 0 if (l := len(foo))%16 == 0 else 1 ): not what you want? If not, what is the logic you're looking for?
It is just what I'm looking for! Thank you very much! Either I read over it or it wasn't already there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.