[issue34517] Error referencing local variables in dict comprehensions inside class definitions

Mark Dickinson report at bugs.python.org
Mon Aug 27 06:00:14 EDT 2018


Mark Dickinson <dickinsm at gmail.com> added the comment:

[I wrote this before Serhiy posted his reply; sending it anyway, in case the doc links are useful.]

This is documented, by-design behaviour. Essentially name resolution skips class scopes.

See https://docs.python.org/3/reference/executionmodel.html#resolution-of-names, and particularly the example at the end of that section, which is very similar to your example.

See also: https://docs.python.org/3/reference/expressions.html#displays-for-lists-sets-and-dictionaries, and in particular this part:

> However, aside from the iterable expression in the leftmost for clause,
> the comprehension is executed in a separate implicitly nested scope.
> This ensures that names assigned to in the target list don’t “leak” into
> the enclosing scope.

That "leftmost for clause" bit explains why, in the following example, the first comprehension is evaluated successfully, but the second raises a `NameError`.

>>> class A:
...     a = 3
...     b = [x+y for x in range(a) for y in range(3)]  # okay
...     c = [x+y for x in range(3) for y in range(a)]  # raises

----------
nosy: +mark.dickinson -serhiy.storchaka
resolution: duplicate -> not a bug
stage: resolved -> 
superseder: improper scope in list comprehension, when used in class declaration -> 

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue34517>
_______________________________________


More information about the Python-bugs-list mailing list