[Python-ideas] PEP 572 version 2: Statement-Local Name Bindings
Chris Angelico
rosuav at gmail.com
Sun Mar 25 00:00:14 EDT 2018
On Sun, Mar 25, 2018 at 2:59 PM, Ethan Furman <ethan at stoneleaf.us> wrote:
> On 03/24/2018 08:51 PM, Chris Angelico wrote:
>>
>> On Sun, Mar 25, 2018 at 2:48 PM, Ethan Furman wrote:
>>>
>>> On 03/24/2018 01:35 AM, Nick Coghlan wrote:
>>>
>>>> In comprehensions and generator expressions, we'd need to explain why
>>>> inline assignments in the outermost iterator
>>>> expression leak but those in filter expressions, inner iterator
>>>> expressions, and result expressions don't.
>>>
>>>
>>> I don't understand -- could you give an example?
>>
>>
>> Let's suppose we have assignment expressions. I'm going to use "(expr
>> as name)" syntax for this example.
>>
>> a = [(1 as b) for c in (d as e) if (2 as f)]
>>
>> Which of these six names is local to the comprehension and which can
>> leak? Due to the requirements of class scope, 'd' must be looked up in
>> the outer scope. That means that its corresponding 'as e' must also
>> land in the outer scope. [...]
>
>
> Why?
>
> d = 9
> def func():
> e = d
>
> d is looked up outside of func, but e is still local to func.
No, it's looked up inside func, and the value is found outside of
func. Consider:
d = 9
def func():
e = d
d = 1
What's happening with a comprehension is more like:
d = 9
def func(_iter):
... body of comprehension
func((d as e))
which is looking it up _outside_ the function, then passing it as a parameter.
ChrisA
More information about the Python-ideas
mailing list