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

Steven D'Aprano steve at pearwood.info
Wed Nov 29 23:04:41 EST 2017


On Thu, Nov 30, 2017 at 11:21:48AM +1300, Greg Ewing wrote:

> 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.

I hadn't thought of that interpretation before, but now that Greg 
mentions it, its so obvious-in-hindsight that I completely agree with 
it. I think that we should promote this as the "one obvious" 
interpretation.

Obviously as a practical matter, there are some x (namely iterators) 
where you cannot extract items without modifying x, but in all other 
cases I think that the pattern-matching interpretation is superiour.


> 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.

Indeed.


> 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.

I'm still in 100% agreement with all of this.


> 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.

To be clear, I'm still luke-warm on the need for this, I think islice is 
adequate, but if others believe this is a use-case important enough for 
a syntactic solution, I've come around to making ... my prefered syntax.


-- 
Steve


More information about the Python-ideas mailing list