You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
List comprehensions now have access to the enclosing class scope #104374
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.
changed the title [-]List comprehension now have access to the enclosing class scope[/-][+]List comprehensions now have access to the enclosing class scope[/+]on May 11, 2023
Activity
[-]List comprehension now have access to the enclosing class scope[/-][+]List comprehensions now have access to the enclosing class scope[/+]asishm-wk commentedon May 11, 2023
on 3.10.8 - this prints [1,2,3]JelleZijlstra commentedon May 11, 2023
I don't think so. I just confirmed on 3.10.9 (don't have a 3.10.8 around), and it throws a NameError. Make sure you run the sample in a class scope.
asishm-wk commentedon May 11, 2023
sorry, you're right! - I forgot to restart the interpreter when testing different variations - so there was already a
ydefined in the outer scope!carljm commentedon May 11, 2023
I started a Discourse thread about options for handling this: https://discuss.python.org/t/pep-709-one-behavior-change-that-was-missed-in-the-pep/26691
carljm commentedon May 13, 2023
I filed a SC issue about this: python/steering-council#189
pythongh-104374: don't inline comprehensions in non-function scopes
pythongh-104374: Remove access to class scopes for inlined comprehens…
gh-104374: Remove access to class scopes for inlined comprehensions (#…