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

Nick Coghlan ncoghlan at gmail.com
Thu Mar 29 10:55:33 EDT 2018


On 28 March 2018 at 00:52, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 03/25/2018 09:46 AM, Ethan Furman wrote:
>>
>> On 03/24/2018 09:24 PM, Nick Coghlan wrote:
>>
>>> No, the fact that the expression defining the outermost iterable gets
>>> evaluated in the outer scope is behaviour that's
>>> explicitly tested for in the regression test suite.
>>>
>>> The language reference spells out that this is intentional for generator
>>> expressions, where it has the added benefit of
>>> reporting errors in the outermost iterable expression at the point where
>>> the genexp is defined, rather than at the point
>>> where it gets iterated over:
>>> https://docs.python.org/3/reference/expressions.html#generator-expressions
>>>
>>> Independently of the pragmatic "getting them to work sensibly at class
>>> scope" motivation, comprehensions inherit those
>>> semantics by way of the intended semantic equivalence between "[x for x
>>> in sequence]" and "list(x for x in sequence)".
>>
>>
>> Thank you (everyone!) for your patience.
>>
>> Using the latest example from Angelico and myself:
>>
>> --> d = 9
>> ... def func(_iter):
>> ...     ... body of comprehension
>> --> func((d as e))
>>
>> The sticking point is the `func((d as e))`, which to my mind should happen
>> inside the comprehension, but needs to happen
>> outside -- and the reason it has to happen outside is so that the
>> interpretor can verify that `d` actually exists;
>> however, I think we can have both:
>>
>> --> def func(_iter):
>> ...     ...
>> ...     e = d
>> ...     ...
>> --> d
>> --> func()
>>
>> This way, the assignment does not leak, but the referenced name is still
>> looked up and verified to exist outside the
>> function call.
>>
>> I don't know how easy/difficult that would be to implement.  At this point
>> a simple confirmation that I understand and
>> that in theory the above would solve both issues is what I'm looking for.
>> Or, of course, the reasons why the above
>> would not, in theory, work.
>
>
> Any insights here?  I would rather not say the same things in another thread
> if we can resolve this question here and be done with it.  :)

Just what Chris said earlier: the expression defining the outermost
iterable can be arbitrarily complex, and what you're suggesting would
only be feasible for a top-level name binding, not for nested ones.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list