Calling a generator multiple times

Oren Tirosh oren-py-l at hishome.net
Sat Dec 8 07:31:57 EST 2001


On Fri, Dec 07, 2001 at 01:20:42AM +0000, Courageous wrote:
> After I posted my message, it occured to me that I wasn't
> addressing a key part of the semantics, namely the ability
> for multiple consumers to generate the generator multiple
> times. 

The problem with a generic restartable generator is what to do about any
arguments to the generator function.  If you want the consumer to be able 
to blindly iter() your generator as if it were a list or any other 
container you must pack your arguments along.

Here's a functor object for doing that:

class xiter:
    def __init__(self, func, *args):
        self.func = func
        self.args = args

    def __iter__(self):
        return self.func(*self.args)

Notes:
  The resulting object behaves like a container: it has an __iter__ method
  with no arguments that may be called multiple times, returning
  independent iterators of the same source.  If the underlying function
  uses only its arguments and does not modify them these iterators should
  step through the same sequence.

  This is not specific to generator functions.  It can work with any function 
  that returns an iterator. 

  Why xiter?  This is inspired by xrange and xreadlines.  They are iterable 
  objects that act as a deferred-execution version of a function with the 
  same name sans the 'x'.  

  In the case of xreadlines the analogy isn't perfect. The function 
  xreadlines.xreadlines is started with __call__, not __iter__ so it does not 
  emulate a container.  Since it takes no arguments it could have been an 
  object's __iter__ method and that object would then behave as a container.
  An xrange object emulates a container correctly - it can produce
  multiple, independent iterators of itself.

	Oren





More information about the Python-list mailing list