[Python-Dev] The iterator story

Paul Svensson paul-python@svensson.org
Fri, 19 Jul 2002 16:52:42 -0400 (EDT)


On Fri, 19 Jul 2002, Neil Schemenauer wrote:

>__iter__ is not a flag.  When you want to loop over an object you call
>__iter__ to get an iterator.  Since you should be able to loop over all
>iterators they should provide a __iter__ that returns self.

But you don't really loop _over_ the iterator, you loop _thru_ it.

To me there's a fundamental difference between providing a new object
and providing a reference to an existing object.  This difference
is mostly noticable for objects containing state.  The raison d'etre
for iterators is to contain state.  If it's sensible to sometimes
return an old object and sometimes a new, then we could as well have
'list(x) is x' being true when x is already a list.

What I'm trying to get to is, __iter__(x) returning an existing
object (self in this case) is really something very much different
from __iter__() creating new state, and returning that.

The problem is that we do want a way to loop _thru_ an iterator,
and having __iter__() return self gives us that, at the cost
of the above mentioned confusing conflagration.

Ping's suggested seq() function solves that quite nicely:

class seq:
    def __init__(self, i):
        self._iter = i
    def __iter__(self):
        return self._iter


		/Paul