reseting an iterator

Terry Reedy tjreedy at udel.edu
Wed May 20 16:45:59 EDT 2009


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?

No.  Such a method would have to poke around in the internals of the 
__next__ function in implementation specific ways.  The values used to 
initialize that function might have changed, so 'reset' would have to be 
carefully defined.

def squares():
   start = int(input("enter starting int:"))
   stop  = int(input("enter stopping int"))
   for i in range(start,stop):
     yield i*i

What does 'reset' mean here?

> 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, 

This is so that 'iter(iterator) is iterator', so that functions can take 
either an interable or iterator as an argument and proceed without 
checking which it got.

> and once a call ITERATOR. __next__() raises StopIteration every
 >  such subsequent call does the same.

After returning objects for some number of calls, which might be unbounded.

The protocol is basically one method with defined behavior.  It is 
intentionally minimal so it can be used as the universal within-Python 
object stream protocol.  Multiple ways of getting interators is in line 
with this purpose.

Terry Jan Reedy




More information about the Python-list mailing list