Misleading error message of the day

Robert Kern robert.kern at gmail.com
Thu Dec 8 14:57:15 EST 2011


On 12/8/11 4:21 PM, Chris Angelico wrote:
> 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.

unpack_iterable() has the original object available to it, not just the 
iterator. It could opportunistically check for __len__() and fall back to the 
less informative message when it is absent.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list