[Python-Dev] Termination of two-arg iter()
Brett Cannon
drifty@bigfoot.com
Sun, 14 Jul 2002 01:16:10 -0700 (PDT)
[Oren Tirosh]
> At the time this was discussed on the list has anyone considered the
> possibility of raising an exception? Something like 'IteratorExhausted'?
>
I have no idea whether this was discussed before or not, but I personally
don't like the idea of having another exception being raised by iterators.
Without reading the PEP this exact second, my gut response is that
iterators should have a single exception that signals it has reached its
end. It seems like StopIteration is saying "stop please" and
IteratorExhausted would be like screaming "STOP CALLING .next()!!!".
Either you force them to get the clue the first time or you let them
continue being rude; Python shouldn't need to raise its voice and act like
an over-bearing parent. If we wanted over-bearing parents we would be
yelling for typing of arguments. =)
<snip>
> Iterable objects can often serve as a replacement for lists in many places
> and even passed successfully to a lot of old code that was written before
> the iteration protocol. But an iterable object is not always a suitable
> replacement for a sequence when the code needs to iterate multiple times and
> the object is not re-iterable. This will fail in a very nonobvious way
> without raising an exception because an exhausted iterator looks just like
> an empty sequence to a for loop.
>
After reading this email I felt like not raising StopIteration
continuously was like warning that once you hit \0 in a C char array you
have reached the end of the string, but keep going if you care to. We all
know that ain't a good idea. =)
Personally, I say continuously raise StopIteration. I feel that
StopIteration says the iterator is done, period. Being able to go beyond
the signalled end seems like it is not a true once-through iterator with
an actual end but starting to seem like a stream. I thought the point of
putting in something like the sentinel was so that you could force the end
of an iterator and just have it be a suggestion.
I can also see beginners being bitten by this; if people as experienced as
Oren are getting bitten by this we know some person starting out
definitely will be. I know I thought that StopIteration was continuously
raised until the emails on this subject started. When I blindly read
"StopIteration", I don't feel this is a warning that one shouldn't keep
going but a notice that the iterator is done, thanks for coming but please
don't come again (unless restartable iterators are supported =). In other
words, I feel that StopIteration sounds like a notice that the end has
occured and you can't do any more then an advisement that you should stop.
>
> Oren
>
-Brett C.