[Python-ideas] Generator unpacking
Paul Moore
p.f.moore at gmail.com
Mon Feb 15 03:12:16 EST 2016
On 14 February 2016 at 07:43, Nick Coghlan <ncoghlan at gmail.com> wrote:
> On 14 February 2016 at 07:40, Greg Ewing <greg.ewing at canterbury.ac.nz>
> wrote:
>>
>>
>> Another possibility is
>>
>> a, b, ... = value
>
>
> Now, *that* spelling to turn off the "implicit peek" behaviour in iterable
> unpacking I quite like.
>
> arg_iter = iter(args)
> command, ... = arg_iter
> run_command(command, arg_iter)
>
> Although again, the main downside would be that "..." here means something
> rather different from what it means as a subscript element.
IMO, the other downside is that the semantic difference between
a, b, ... = value
and
a, b, *_ = value
is very subtle, and (even worse) only significant if value is an
iterable as opposed to a concrete container such as a list.
IMO, explicit is better than implicit here, and itertools.islice is
the right way to go:
>>> i = iter(range(10))
>>> a, b = islice(i,2)
>>> a
0
>>> b
1
>>> list(i)
[2, 3, 4, 5, 6, 7, 8, 9]
(And of course in my first attempt I forgot I needed iter(range(...))
as range is not a pure iterable - proving my point about the subtle
semantics!)
Paul
More information about the Python-ideas
mailing list