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

Greg Ewing greg.ewing at canterbury.ac.nz
Thu Nov 30 00:32:02 EST 2017

Brendan Barnwell wrote:
> That's an interesting analysis, but I don't think your view is 
> really the right one.  It *is* unpacking a suitcase, it's just that *if 
> necessary* the suitcase is constructed just in time for you to unpack 
> it.

I don't think that's right. An iterator created from a sequence
is not a container in its own right, it's something that provides
access to a container. It's not a suitcase, it's a view of the
contents of a suitcase.

> If you expect your suitcase to remain unopened, 
> it's pretty cold comfort to find that someone has opened it and taken 
> only your pants and shoes but left the rest.

So you think it's somehow better if he takes *all* of your
clothes instead?

Here's another way to think about it. If it's acceptable to
exhaust the iterator when only the first few items are
requested, then you're planning to throw the iterator
away afterwards. In that case, what purpose is served by
extracting the rest of the items? Remember, the ellipsis
explicitly says you don't care how many more items there

The only reason I can think of is if you're relying on
side effects performed by the iterator, which is a
pretty obscure way to design code. If the iterator
really must be exhausted for some reason, it would be
better to be explicit about it, e.g.

    a, b, ... = spam_iterator
    for _ in spam_iterator:
       pass # Mustn't leave any spam in the fridge or it will go bad


More information about the Python-ideas mailing list