[Python-ideas] PEP 572: Statement-Local Name Bindings
Chris Angelico
rosuav at gmail.com
Wed Feb 28 09:56:21 EST 2018
On Thu, Mar 1, 2018 at 1:51 AM, Serhiy Storchaka <storchaka at gmail.com> wrote:
> 28.02.18 16:06, Chris Angelico пише:
>>
>> On Thu, Mar 1, 2018 at 12:49 AM, Serhiy Storchaka <storchaka at gmail.com>
>> wrote:
>>>
>>> Other options:
>>>
>>> g = (f(x) for x in range(5))
>>> stuff = [[y, y] for y in g]
>>
>>
>> That's the same as the one-liner, but with the genexp broken out. Not
>> sure it helps much as examples go?
>
>
> It is more readable. But can't be used as an expression.
>
>>> 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
ChrisA
More information about the Python-ideas
mailing list