-
-
Notifications
You must be signed in to change notification settings - Fork 29.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Error referencing local variables in dict comprehensions inside class definitions #78698
Comments
This code: Produces following error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 3, in A
File "<input>", line 3, in <dictcomp>
NameError: name 'a' is not defined Which i think it shouldn't produce. Issue occurs only in dict comprehensions inside class definitions referencing class attributes(which are in local scope during definition). |
Update: any class definition comprehension referencing local variables inside filtering block produces this error. |
This is a duplicate of bpo-3692. |
[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:
That "leftmost for clause" bit explains why, in the following example, the first comprehension is evaluated successfully, but the second raises a >>> 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 |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: