[Python-ideas] iterable.__unpack__ method

Chris Angelico rosuav at gmail.com
Sat Feb 23 11:18:49 CET 2013


On Sat, Feb 23, 2013 at 8:14 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> It would be much easier, and have much the same effect, if unpacking simply
> requested the minumum number of items and stopped raising a ValueError if
> the iterator has more items. No new protocol is needed. Guido rejected this
> as silently masking errors.

What if it were done explicitly, though?

Currently:
>>> a,b,c=range(3)
>>> a,b,c=range(4)
Traceback (most recent call last):
  File "<pyshell#55>", line 1, in <module>
    a,b,c=range(4)
ValueError: too many values to unpack (expected 3)
>>> a,b,c,*d=range(6)
>>> a,b,c,* =range(4)
SyntaxError: invalid syntax

Suppose the last notation were interpreted as "request values for a,
b, and c, and then ignore the rest". This would support infinite
iterators, and would be an explicit statement from the caller that
it's not an error to have more elements. This doesn't solve the
backward-compatibility issue, but it would allow a client to
specifically engage a forward-compatibility mode (by putting ,* after
any unpack that might introduce more elements - of course, you'd need
to be confident that you won't care about those elements).

It can be done with current code, of course.
>>> a,b,c=itertools.islice(range(6),3)
But this has significant overhead in verbiage, where a simple ",*"
would carry the same sort of meaning it does in other contexts.

ChrisA



More information about the Python-ideas mailing list