revive a generator
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Oct 22 01:39:59 EDT 2011
More information about the Python-list mailing list
Sat Oct 22 01:39:59 EDT 2011
- Previous message (by thread): revive a generator
- Next message (by thread): revive a generator
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Fri, 21 Oct 2011 16:25:47 -0400, Terry Reedy wrote: > 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) We can do that even more simply, using a slightly different interface. >>> from functools import partial >>> sq3 = partial(squares, 3) sq3 is now an iterator factory. You can't iterate over it directly, but it's easy to restart: just call it to return a fresh iterator. >>> list(sq3()) [0, 1, 4] >>> list(sq3()) [0, 1, 4] -- Steven
- Previous message (by thread): revive a generator
- Next message (by thread): revive a generator
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list