[Python-ideas] PEP 572 version 2: Statement-Local Name Bindings

Paul Moore p.f.moore at gmail.com
Sat Mar 24 08:06:30 EDT 2018


On 24 March 2018 at 11:55, Chris Angelico <rosuav at gmail.com> wrote:
> On Sat, Mar 24, 2018 at 10:49 PM, Paul Moore <p.f.moore at gmail.com> wrote:
>> On 24 March 2018 at 09:18, Chris Angelico <rosuav at gmail.com> wrote:
>>> Except that a list comprehension is implemented using an inner
>>> function. Very approximately:
>>>
>>> x = [n * m for n in range(4) for m in range(5)]
>>>
>>> def <listcomp>(iter):
>>>     ret = []
>>>     for n in iter:
>>>         for m in range(5):
>>>             ret.append(n * m)
>>>     return ret
>>> x = <listcomp>(iter(range(4))
>>>
>>> So the first (outermost) iterable is actually evaluated in the
>>> caller's scope, but everything else is inside a subscope. Thus an
>>> assignment inside that first iterable WILL leak into the surrounding
>>> scope; but anywhere else, it won't.
>>
>> Wow, that's subtle (in a bad way!). I'd much rather that assignments
>> don't leak at all - that seems to me to be the only correct design,
>> although I understand that implementation practicalities mean it's
>> hard to do.
>>
>> There's a lot of context snipped here. Is this about the variant that
>> just does assignment without the new scope? If it is, then is there a
>> similar issue with the actual proposal, or is that immune to this
>> problem (I suspect that it's not immune, although the details may
>> differ).
>
> The code equivalence I gave above applies to the existing Python
> semantics. I'm not sure why the outermost iterable is evaluated in its
> enclosing context, but there must have been a good reason.

Understood. But the current Python semantics doesn't have any way of
binding a name as part of that outermost iterable. It's the
interaction of the new feature (name binding in expressions) with the
existing implementation (the first iterable is outside the constructed
scope for the comprehension) that needs to be clarified and if
necessary modified to avoid nasty consequences.

Paul


More information about the Python-ideas mailing list