[Python-ideas] How assignment should work with generators?

Greg Ewing greg.ewing at canterbury.ac.nz
Wed Nov 29 17:21:48 EST 2017

C Anthony Risinger wrote:

> `a, b, ...` to me says "pull out a and b and throw away the rest"... 
 > The mere presence of more
> characters (...) implies something else will *happen* to the remaining 
> items, not that they will be skipped.

It seems that many people think about unpacking rather
differently from the way I do. I think the difference
is procedural vs. declarative.

To my way of thinking, something like

    a, b, c = x

is a pattern-matching operation. It's declaring that
x is a sequence of three things, and giving names to
those things. It's not saying to *do* anything to x.

With that interpretation,

    a, b, ... = x

is declaring that x is a sequence of at least two
items, and giving names to the first two. The ellipsis
just means that there could be more items, but we
don't want to give them names.

On the other hand, some people seem to be interpreting
the word "unpack" as in "unpack a suitcase", i.e. the
suitcase is empty afterwards. But unpacking has never
meant that in Python! If it did, then

    x = [1, 2, 3]
    a, b, c = x

would leave x == [] afterwards.

The only case where unpacking behaves like that is when
the rhs is an iterator rather than a sequence, in which
case a side effect is unavoidable. The question then is
what the side effect should be.

I would argue that, since the side effect is something
that's not really wanted, it should be as *small* as
possible. By that argument,

    a, b, ... = some_iterator

should do as *little* as possible to fulfill what's
being asked, i.e. give names to the first two items
produced by the rhs. Consuming those two items is
unavoidable, but there's no need to consume any more.

As for the "extra syntax", we only need it because we've
defined the existing unpacking syntax to imply verifying
that the rhs has exactly the same length as the pattern.

We now want to express patterns which don't impose
a length constraint, so we need to write them some
other way.


More information about the Python-ideas mailing list