[Python-Dev] Termination of two-arg iter()
Oren Tirosh
oren-py-d@hishome.net
Sun, 14 Jul 2002 07:05:13 -0400
On Sun, Jul 14, 2002 at 01:16:10AM -0700, Brett Cannon wrote:
> [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. =)
This anthropomorphic description has too many irrelevant associations. Let's
leave the parents out of this.
The logic is simple: StopIteration is not an error. It's not even a warning,
it's a normal part of program operation. It uses the exception mechanism
because it is the most convenient form of out-of-band signalling. The
hypothetical IteratorExhausted is an error. The fact that both of them
happen to be exceptions is almost a coincidence.
Unlike IndexError which is sometimes used to bail out of loops the
IteratorExhausted exception is almost guaranteed to be a programmer error.
And it's error that would otherwise pass silently and produce strange
results.
> definitely will be. I know I thought that StopIteration was continuously
> raised until the emails on this subject started.
For most Python iterators it is. This behavior is OK but it could be changed
to something stricter. So far I thought this behavior was mandatory so I
didn't raise this proposal. Now I learned that officially it is undefined
and that this behavior is just what most Python iterators do so it could be
possible to change it to something safer.
Oren