Author terry.reedy
Recipients Martin Hosken, eamanu, terry.reedy
Date 2019-03-15.21:11:08
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
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:09terry.reedysetrecipients: + terry.reedy, eamanu, Martin Hosken
2019-03-15 21:11:09terry.reedysetmessageid: <>
2019-03-15 21:11:09terry.reedylinkissue36300 messages
2019-03-15 21:11:08terry.reedycreate