[Python-Dev] Informal educator feedback on PEP 572 (was Re: 2018 Python Language Summit coverage, last part)

Paul Moore p.f.moore at gmail.com
Mon Jun 25 09:46:31 EDT 2018

On 25 June 2018 at 13:24, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 25 June 2018 at 22:17, Nick Coghlan <ncoghlan at gmail.com> wrote:
>> FWIW, the most cryptic parent local scoping related exception I've
>> been able to devise so far still exhibits PEP 572's desired "Omitting
>> the comprehension scope entirely would give you the same name lookup
>> behaviour" semantics:
>>     >>> def outer(x=1):
>>     ...     def middle():
>>     ...         return [x := x + i for i in range(10)]
>>     ...     return middle()
>>     ...
>>     >>> outer()
>>     Traceback (most recent call last):
>>         ...
>>     NameError: free variable 'x' referenced before assignment in enclosing scope
>> It isn't the parent local scoping, or even the assignment expression,
>> that's at fault there, since you'd get exactly the same exception for:
>>     def outer(x=1):
>>         def middle():
>>             x = x +1
>>             return x
>>         return middle()
> Oops, I didn't mean to say "exactly the same exception" here, as the
> whole reason I'd settled on this example as the most cryptic one I'd
> found so far was the fact that the doubly nested version *doesn't*
> give you the same exception as the singly nested version: the version
> without the comprehension throws UnboundLocalError instead.

At the level of "what my intuition says" the result is the same in
both cases - "it throws an exception". I have no intuition on *which*
exception would be raised and would experiment (or look up the
details) if I cared.

> However, the resolution is the same either way: either 'x' has to be
> declared as 'nonlocal x' in 'middle', or else it has to be passed in
> to 'middle' as a parameter.

Once someone told me that's what I needed, it's sufficiently obvious
that I'm fine with that. If no-one was able to tell me what to do, I'd
simply rewrite the code to be less obfuscated :-)

I've probably explained my intuition enough here. If we debate any
further I'll just end up knowing what's going on, destroying my value
as an "uninformed user" :-)

More information about the Python-Dev mailing list