Terry J. Reedy <tjre...@udel.edu> added the comment:

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.

----------
nosy: +terry.reedy
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed
title: eval of generator expressions cannot access local variables -> eval of 
comprehension cannot access local variables
versions:  -Python 2.7, Python 3.6

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue36300>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to