[issue30346] Odd behavior when unpacking `itertools.groupby`

Tim Peters report at bugs.python.org
Sat May 13 13:39:11 EDT 2017


Tim Peters added the comment:

Users certainly have been fooled by this, although "unpacking" is a red herring.  I've been burned by it, and I've seen StackOverflow puzzles related to the same thing.  I think this is the heart of it:  given a finite iterable I, it usually makes no semantic difference whether a program does:

    for thing in I:
    
or

    for thing in list(I):
    
But when `I` is obtained from `groupby()`, `thing` contains an iterator that shares state with `I` itself, so they're not at all the same.  It's surprising just because it's so uncommon.  "unpacking" is one special case of this.

I'd like to see an attempt to invoke a sub-iterator raise an exception if the primary iterator has moved beyond it.  The behavior in that case now is undefined, utterly accidental, and useful only for surprising people ;-)  Nobody _intends_ to do this, unless they have no idea how `groupby()` is meant to be used.

----------
nosy: +tim.peters

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue30346>
_______________________________________


More information about the Python-bugs-list mailing list