Reset a generator function?

Oren Tirosh oren-py-l at hishome.net
Wed Sep 11 01:14:00 EDT 2002


On Tue, Sep 10, 2002 at 07:31:07PM +0000, Robert Oschler wrote:
> How can I reset a generator function so that it begins yielding values as
> it did when first called?

You need to call the function again with the same arguments. Assuming that
its result depends only on the arguments and that it does not modify them
it should regenerate the same sequence.

Look at the regen function in http://tothink.com/python/dataflow/xlazy.py
It wraps a generator function with a wrapper class that behaves just like
the generator function except that its return value is an iterable object
instead of an iterator. Each time iter() is called on this object it calls 
the generator function again with the original arguments.

example:

>>> from __future__ import generators
>>> def f(n):
...   for i in xrange(n):
...     yield i*10
...
>>> x=f(10)
>>> list(x)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> list(x)
[]
>>>
>>> from xlazy import *
>>> f = regen(f)
>>>
>>> x = f(10)
>>> list(x)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> list(x)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
>>>

	Oren




More information about the Python-list mailing list