Misleading error message of the day

Chris Angelico rosuav at gmail.com
Thu Dec 8 11:21:31 EST 2011


On Fri, Dec 9, 2011 at 2:55 AM, Andrea Crotti <andrea.crotti.0 at gmail.com> wrote:
> Yes but how do you know how many values you generated when it quits?
> I mean I don't know how it work internally, but it should keep a temporary
> list of the yielded values to be able to find out how many values are
> there..

Iterator unpacking works roughly thus:

1) Count up how many results you need (call that N)
2) N times, get a value from the iterator. If StopIteration is raised,
swallow it and raise ValueError because there were too few values.
3) Attempt to get one more value from the iterator. If StopIteration
is NOT raised, raise ValueError because there were too many values.

At no point is the "total size" of the iterator counted (it could,
after all, be infinite). When ValueError is raised, all that's known
is that StopIteration wasn't raised at the end of the process.

ChrisA



More information about the Python-list mailing list