[Python-ideas] Generator unpacking

Nick Coghlan ncoghlan at gmail.com
Sat Feb 13 08:06:22 EST 2016


On 13 February 2016 at 17:59, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Andrew Barnert via Python-ideas wrote:
>>
>> I think what you're _really_ suggesting here is that there should be a way
>> to
>> unpack iterators lazily,
>
>
> Seems to me you should be able to write
>
>   a, b, * = some_iter
>
> as a way of saying "I don't care about the rest of the values".

The main problem with that specific spelling of the idea is that it's
the inverse of what the bare "*" means when declaring function
parameters - there, it's a way of marking the end of the positional
arguments, when you want to put keyword only arguments after it.

The other problem is that it makes:

    a *= value

and

    a, b, *= value

mean wildly different things.

Where these discussions generally end up is:

1. The cases where you actually want "unpack this many values, ignore
the rest" are pretty rare
2. When you do really need it, islice handles it
3. Adding new syntax isn't warranted for a relatively rare use case
the stdlib already covers

Probably the most plausible idea would be a "head()" recipe that does
something like:

    def head(iterable, n):
        itr = iter(iterable)
        return tuple(islice(itr, n)), itr

Usable as:

    (a, b), rest = head(iterable, 2)

Making it a recipe means folks can customise it as they wish (e.g.
omitting the tuple call)

However, I'm not sure how much that would actually help, since using
islice directly here is already pretty straightforward (once you know
about it), and for small numbers of items, you can also just use the
next builtin if you know you have an iterator:

    itr = iter(iterable)
    a = next(itr)
    b, c = next(itr), next(itr)

Cheers,
Nick.

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


More information about the Python-ideas mailing list