Callable generators (PEP 288: Generator Attributes, again)

Michele Simionato mis6 at pitt.edu
Tue Nov 18 09:16:43 EST 2003


francisgavila at yahoo.com (Francis Avila) wrote in message news:<55688f89.0311180211.7ab1bc30 at posting.google.com>...

I looked at that PEP few months ago and I came out with an iterator class.
Here it is:

"""An object-oriented interface to iterators-generators"""

class Iterator(object):
    """__gen__ is automatically called by __init__, so must have signature
    compatibile with __init__. Subclasses should not need to override __init__:
    you can do it, but you must do it cooperatively or, at least, ensure that
    __gen__ is called correctly and its value assigned to self.iterator. 
    """
    def __init__(self,*args,**kw):
        super(Iterator,self).__init__(*args,**kw)
        self.iterator=self.__gen__(*args,**kw)
    def __gen__(self,*args,**kw):
        "Trivial generator, to be overridden in subclasses"
        yield None
    def __iter__(self):
        return self
    def next(self):
        return self.iterator.next()

class MyIterator(Iterator):
    def __gen__(self):
        self.x=1
        yield self.x # will be changed outside the class
        yield self.x

iterator=MyIterator()

print iterator.next()
iterator.x=5
print iterator.next()

Wrapping the generator in the class, I can pass parameters to it (in
this case x). IOW, here the generator has an explicit "self" rather
than an implicit "__self__" as in the PEP. I am not sure if I like the 
PEP, wouldn't be easier to have a built-in iterator class?


          Michele Simionato




More information about the Python-list mailing list