revive a generator
Terry Reedy
tjreedy at udel.edu
Fri Oct 21 16:25:47 EDT 2011
Here is a class that creates a re-iterable from any callable, such as a
generator function, that returns an iterator when called, + captured
arguments to be given to the function.
class reiterable():
def __init__(self, itercall, *args, **kwds):
self.f = itercall # callable that returns an iterator
self.args = args
self.kwds = kwds
def __iter__(self):
return self.f(*self.args, **self.kwds)
def squares(n):
for i in range(n):
yield i*i
sq3 = reiterable(squares, 3)
for i in sq3: print(i)
for i in sq3: print(i)
>>>
0
1
4
0
1
4
--
Terry Jan Reedy
More information about the Python-list
mailing list