reseting an iterator

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed May 20 20:47:47 EDT 2009


On Wed, 20 May 2009 11:35:47 -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?

No.

def gen():
    for name in os.listdir('.'):
        yield open(name).read()
        os.remove(name)


How would you "easily" reset this generator so that it returns the same 
values each time?

That's an extreme example, but as a general rule, generators/iterators 
are one-shot: having consumed a value, you can't get it back again 
without re-creating it from scratch, or possibly not even then. Here's a 
less destructive example:

def gen():
    for i in xrange(10):
        yield time.time()



-- 
Steven



More information about the Python-list mailing list