[Python-Dev] Termination of two-arg iter()

Tim Peters tim.one@comcast.net
Sat, 13 Jul 2002 23:15:50 -0400


[Guido]
> Actually, not.  Under "Resolved Issues" the PEP has this:
>
>     - Once a particular iterator object has raised StopIteration, will
>       it also raise StopIteration on all subsequent next() calls?
>       Some say that it would be useful to require this, others say
>       that it is useful to leave this open to individual iterators.
>       Note that this may require an additional state bit for some
>       iterator implementations (e.g. function-wrapping iterators).
>
>       Resolution: once StopIteration is raised, calling it.next()
>       continues to raise StopIteration.
>
> So I misremembered, and Tim didn't read the PEP closely enough. :-)

Not so.  I read the PEP *very* closely, twice even.  It's just that both
times, I gave up in boredom a few points above that one <wink>.  I think I
used to know it, though, and made sure StopIteration is a sink state for
generator-iterators because of it.

> ...
> Hm.  Given what the PEP says, I'm ready to have this fixed (even in
> 2.2.2).

Well, the PEP proper just doesn't say.  In a court of Standard Law, I'm
pretty sure the "Resolved Issues" section would be ruled to be in the nature
of a non-normative appendix.  Now that the PSF has some funds, I'm sure we
can buy that decision if need be <wink>.

> I can't call code relying on this sane.

Now that I've seen what it actually does, I think it's kind of cute.  Like

f = file('somefile')
get = iter(f.readline, '\n')

while 1:
    paragraph = list(get)
    if not paragraph:
        break
    # deal with paragraph, a list of lines

The only big problem is that once you hit the end of the file, this hangs in
an infinite loop inside the list() implementation, accumulating an unbounded
number of empty strings.  But that just makes it extra cute.  Cute enough to
be insane, probably.