[Python-ideas] PEP 572 version 2: Statement-Local Name Bindings
Guido van Rossum
guido at python.org
Sun Mar 25 00:27:10 EDT 2018
On Sat, Mar 24, 2018 at 7:08 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 25 March 2018 at 02:34, Eric Fahlgren <ericfahlgren at gmail.com> wrote:
>
>> On Sat, Mar 24, 2018 at 7:14 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
>>
>>>
>>> >>> class C:
>>> ... sequence = range(10)
>>> ... listcomp = [x for x in sequence]
>>>
>>
>> >>> class C:
>> ... y = 1
>> ... sequence = range(10)
>> ... listcomp = [x+y for x in sequence]
>> ...
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> File "<stdin>", line 4, in C
>> File "<stdin>", line 4, in <listcomp>
>> NameError: name 'y' is not defined
>>
>> Ok, so how does 'y' fit into these scoping rules?
>>
>
> Everything except the outermost iterator is evaluated in the implicitly
> nested scope, so comprehensions at class scope have the restriction that
> only the outermost iterator can access names defined in the class scope. It
> turned out that was enough to preserve compatibility with most of the
> comprehensions that folks actually use at class scope.
>
> For those rare cares where it isn't, the typical resolution is to either
> define a helper function, or else switch to a regular for loop.
>
Just in case anyone wonders, I don't think the special rules around class
scope count are a wonderful feature. 28 years ago it was the best we could
do, and by the time we realized its problems -- all rare edge cases for
sure, but unintuitive and hard to debug when they strike -- we were tied by
backward compatibility. And we still are. (At the time there were no nested
scopes, there was just local, global, builtins; class scope was treated as
a function scope and that was that.)
(I have a lot more to say about PEP 572 but I'll do it in the "take three"
thread.)
--
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180324/a3b09284/attachment.html>
More information about the Python-ideas
mailing list