[Python-ideas] A comprehension scope issue in PEP 572
Ethan Furman
ethan at stoneleaf.us
Sun May 13 03:17:48 EDT 2018
On 05/12/2018 11:41 PM, Tim Peters wrote:
> [Tim, suggests changes to the Reference Manual's 4.2.1]
>> """
>> An assignment expression binds the target, except in a function F
>> synthesized to implement a list comprehension or generator expression
>> (see XXX). In the latter case, if the target is not in F's
>> environment (see section 4.2.2) , the target is bound in the block
>> containing F.
>> """
>
> Let me try that again ;-) The notion of "environment" includes the
> global scope, but that's not really wanted here. "Environment" has
> more of a runtime flavor anyway. And since nobody will tell me
> anything about class scope, I read the docs myself ;-)
>
> And that's a problem, I think! If a comprehension C is in class scope
> S, apparently the class locals are _not_ in C's environment. Since C
> doesn't even have read access to S's locals, it seems to me bizarre
> that ":=" could _create_ a local in S.
Python 3.7.0b3+ (heads/bpo-33217-dirty:28c1790, Apr 5 2018, 13:10:10)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
--> class C:
... huh = 7
... hah = [i for i in range(huh)]
...
--> C.hah
[0, 1, 2, 3, 4, 5, 6]
Same results clear back to 3.3 (the oldest version of 3 I have). Are the docs wrong?
Or maybe they just refer to functions:
--> class C:
... huh = 7
... hah = [i for i in range(huh)]
... heh = lambda: [i for i in range(huh)]
...
--> C.hah
[0, 1, 2, 3, 4, 5, 6]
--> C.heh()
Traceback (most recent call last):
File "test_class_comp.py", line 7, in <module>
print(C.heh())
File "test_class_comp.py", line 4, in <lambda>
heh = lambda: [i for i in range(huh)]
NameError: global name 'huh' is not defined
So a class-scope comprehension assignment expression should behave as you originally specified.
--
~Ethan~
More information about the Python-ideas
mailing list