reseting an iterator

J. Cliff Dyer jcd at sdf.lonestar.org
Fri May 22 09:46:33 EDT 2009


On Wed, 2009-05-20 at 11:35 -0700, Jan wrote:
> Wouldn't it be easy for Python to implement generating functions so
> that the iterators they return are equipped with a __reset__() method?
> 
> Here is the context of this question.
> 
> Python documentation defines  a "iterator" as an object ITERATOR
> having methods __next__() and __iter__() such that the call
> ITERATOR.__iter__() returns the object itself, and once a call
> ITERATOR. __next__() raises StopIteration every such subsequent call
> does the same.

You don't need a reset method.  There is no hard and fast rule that
__iter__ must return the object itself.  It just needs to return an
iterator.  For example:

>>> l = [1,2,3]
>>> l.__iter__()
<listiterator object at 0x7fd0da315850>
>>> l is l.__iter__()
False

Just create a class with an __iter__ method that returns a reset
iterator object.


class X(object):
    def __init__(self, max=3):
        self.counter = 0
        self.max = max
    def __iter__(self):
        return self
    def next(self):
        if self.counter < self.max:
            self.counter += 1
            return self.counter
        else:
            raise StopIteration

class Y(object):
    def __iter__(self):
        return X()

In this setup, X has the problem you are trying to avoid, but Y behaves
as a resettable iterable.

>>> x = X()
>>> for c in x:
...     print c
... 
1
2
3
>>> for c in x:
...     print c
... 
>>> y = Y()
>>> for c in y:
...     print c
... 
1
2
3
>>> for c in y:
...     if c < 3:
...         print c
... 
1
2
>>> for c in y:
...     print c
... 
1
2
3

Cheers,
Cliff





More information about the Python-list mailing list