Callable generators (PEP 288: Generator Attributes, again)

Michele Simionato mis6 at
Tue Nov 18 15:16:43 CET 2003

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

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):
    def __gen__(self,*args,**kw):
        "Trivial generator, to be overridden in subclasses"
        yield None
    def __iter__(self):
        return self
    def next(self):

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



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