[Python-Dev] Iterating a closed StringIO

Raymond Hettinger raymond.hettinger at verizon.net
Fri Nov 18 15:29:38 CET 2005


[Guido van Rossum]
> > I hope there isn't anyone here who believes this patch would be a
bad
> idea?

[Nick Coglan]
> Not me, but the Iterator protocol docs may need a minor tweak.
Currently
> they
> say this:
> 
> "The intention of the protocol is that once an iterator's next()
method
> raises
> StopIteration, it will continue to do so on subsequent calls.
> Implementations
> that do not obey this property are deemed broken."


FWIW, here is wording for PEP 342's close() method:

""" 4. Add a close() method for generator-iterators, which raises
       GeneratorExit at the point where the generator was paused.  If
       the generator then raises StopIteration (by exiting normally, or
       due to already being closed) or GeneratorExit (by not catching
       the exception), close() returns to its caller.  If the generator
       yields a value, a RuntimeError is raised.  If the generator
       raises any other exception, it is propagated to the caller.
       close() does nothing if the generator has already exited due to
       an exception or normal exit. """


For Walter's original question, my preference is to change the behavior
of regular files to raise StopIteration when next() is called on an
iterator for a closed file.  The current behavior is an implementation
artifact stemming from a file being its own iterator object.  In the
future, it is possible that iter(somefileobject) will return a distinct
iterator object and perhaps allow multiple, distinct iterators over the
same file.

Also, it is sometimes nice to wrap one iterator with another (perhaps
with itertools or somesuch).  That use case depends on the underlying
iterator raising StopIteration instead of some other exception:

    f = open(somefilename)
    for lineno, line in enumerate(f): 
        . . .


Raymond



More information about the Python-Dev mailing list