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

Serhiy Storchaka storchaka at gmail.com
Wed Feb 28 10:16:09 EST 2018


28.02.18 16:56, Chris Angelico пише:
>>>>       def g():
>>>>           for x in range(5):
>>>>               y = f(x)
>>>>               yield [y, y]
>>>>       stuff = list(g)
>>>
>>>
>>> You're not the first to mention this, but I thought it basically
>>> equivalent to the "expand into a loop" form. Is it really beneficial
>>> to expand it, not just into a loop, but into a generator function that
>>> contains a loop?
>>
>>
>> It is slightly faster (if the list is not too small). It doesn't leak a
>> temporary variable after loop. And in many cases you don't need a list, an
>> iterator would work as well. In these cases it is easy to just drop calling
>> list().
> 
> Doesn't leak a temporary? In Python 3, the list comp won't leak
> anything, but the function is itself a temporary variable with
> permanent scope. You're right about the generator being sufficient at
> times, but honestly, if we're going to say "maybe you don't need the
> same result", then all syntax questions go out the window :D

Explicit for loop leaks variables x and y after the loop. They can hold 
references to large objects. The generator function itself doesn't hold 
references to the proceeded data.



More information about the Python-ideas mailing list