[Python-ideas] Generator unpacking

Oscar Benjamin oscar.j.benjamin at gmail.com
Sat Feb 13 11:36:25 EST 2016


On 13 February 2016 at 13:06, Nick Coghlan <ncoghlan at gmail.com> wrote:
> 1. The cases where you actually want "unpack this many values, ignore
> the rest" are pretty rare

It's not so much ignore the rest but rather retain the rest for
separate consumption. This happens when you want to either peek or
split the first item. For example in parsing a csv file:

def readcsv(csvfile):
    csvfile = map(str.split, csvfile)
    try:
        fieldnames = next(csvfile)
    except StopIteration:
        raise ValueError('Bad csv file')
    return [dict(zip(fieldnames, line)) for line in csvfile]

It would be nicer to write that as something like

    fieldnames, * = csvfile

Another situation where I've wanted that is given an iterable that
yields sequences all of the same length I might want to peek the first
item to check its length before the loop begins.

> 2. When you do really need it, islice handles it

That's true so you can do

    fieldnames, = islice(csvfile, 1)

Somehow I don't like that but really it's fine.

--
Oscar


More information about the Python-ideas mailing list