[Python-ideas] Boundaries for unpacking
Michel Desmoulin
desmoulinmichel at gmail.com
Thu Apr 7 13:03:35 EDT 2016
Python is a lot about iteration, and I often have to get values from an
iterable. For this, unpacking is fantastic:
a, b, c = iterable
One that problem arises is that you don't know when iterable will
contain 3 items.
In that case, this beautiful code becomes:
iterator = iter(iterable)
a = next(iterator, "default value")
b = next(iterator, "default value")
c = next(iterator, "default value")
More often than not, I wish there were a way to specify a default value
for unpacking.
This would also come in handy to get the first or last item of an
iterable that can be empty. Indeed:
a, *b = iterable
*a, b = iterable
Would fail if the iterable's iterator cannot yield at least one item.
I don't have a clean syntax in mind, so I hope some people will get
inspired by it and will make suggestions.
I add a couple of ideas:
a, b, c with "default value" = iterable
a, b, c except "default value" = iterable
a, b, c | "default value" = iterable
But none of them are great.
Another problem is that if you can't use unpacking on generator yielding
1000000 values:
a, b = iterable # error
a, b, c* = iterable # consume the whole thing, and load it in memory
So if I want the 2 first items, I have to go back to:
iterator = iter(iterable)
a = next(iterator)
b = next(iterator)
Now, I made a suggestion to allow slicing on any iterable (or at least
on any iterator), but I'm not going to hold my breath on it:
a, b = iterable[:2] # allow that on generators
or
a, b = iter(iterable)[:2] # allow that
Some have suggested to add a new syntax:
a, b = iterable(:2)
But even just a way to allow to specify that you just want the 2 first
items without unpacking the all iterable would work for me.
Ideally though, the 2 options should be able to be used together.
More information about the Python-ideas
mailing list