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