Message338036
You example is a list comprehension, but no matter. In 3.x, the value of a comprehension is the result of calling a temporary function. Functions access globals and nonlocals but not non-global locals of surrounding contexts. Class locals are an example of the latter.
>>> class C:
... w = 100
... l = [w for x in ("hello", "world")]
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in C
File "<stdin>", line 3, in <listcomp>
NameError: name 'w' is not defined
To see this, one must make sure that the name in question is not also in globals, as it is below.
>>> w = 50
>>> [w for x in ("hello", "world")]
[50, 50]
>>> class C:
... w = 100
... l = [w for x in ("hello", "world")]
...
>>> C.l
[50, 50] # Evaluated global w, not local w.
When one calls eval with separate globals and locals, one is simulating class context. There should be a FAQ entry about this. |
|
Date |
User |
Action |
Args |
2019-03-15 21:11:09 | terry.reedy | set | recipients:
+ terry.reedy, eamanu, Martin Hosken |
2019-03-15 21:11:09 | terry.reedy | set | messageid: <1552684269.09.0.687485779562.issue36300@roundup.psfhosted.org> |
2019-03-15 21:11:09 | terry.reedy | link | issue36300 messages |
2019-03-15 21:11:08 | terry.reedy | create | |
|