Closed
Description
Code:
class X:
y = 1
print([x + y for x in range(3)])
On current main:
Python 3.12.0a7+ (heads/main:94f30c7557, May 10 2023, 17:27:39) [Clang 14.0.0 (clang-1400.0.29.202)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class X:
... y = 1
... print([x + y for x in range(3)])
...
[1, 2, 3]
But on 3.11:
>>> class X:
... y = 1
... print([x + y for x in range(3)])
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in X
File "<stdin>", line 3, in <listcomp>
NameError: name 'y' is not defined
I actually like the new behavior, and I discovered this bug as I was preparing a post proposing that we make things work this way in 3.13. But it's a behavior change, and we should only make this change on purpose and not by accident.
This could plausibly break real code if the name is defined in both the module and class scope, and current code relies on getting the name from the module scope.
cc @carljm
Linked PRs
Metadata
Metadata
Assignees
Projects
Status
Done