[Python-Dev] Single- vs. Multi-pass iterability

Guido van Rossum guido@python.org
Fri, 12 Jul 2002 09:36:22 -0400


> > > I have just submitted a patch that makes a file into an iterator
> > > (i.e. adds a .next method to files).  With this change all Python
> > > objects that have an __iter__ method and no next method produce
> > > iterators that do not modify the container.  Another possibility
> > > would be to make file iterators that use seek or re-open the file to
> > > avoid modifying the file position of the parent file object.  I
> > > don't think that would be a good idea because files can be devices,
> > > pipes or sockets which are not seekable.
> > 
> > Cute trick, but I think it's too fragile.  You don't know about 3rd
> > party iterables that have the same problem as file.
> 
> I don't understand what you mean by fragile. I'm not suggesting anything
> that actually depends on this behavior so I don't see what could break.

If nothing depends on it, what's the point?

> I think it's semantically cleaner for iterable objects to produce
> iterators that do not modify the state of the original iterable
> object.

Too bad.  Files are the only first but certainly not the only example,
and saying it's cleaner doesn't make it so.

> There's no way to force extension writers to adhere to this but
> Python should at least set a good example. Python file objects are
> not a good example. The xrange object that was its own iterator was
> not a good example.

That version of the xrange object was broken.

I don't see what's wrong with the file object.  Iterating over a file
changes the file's state, that's just a fact of life.

--Guido van Rossum (home page: http://www.python.org/~guido/)