Conditionally implementing __iter__ in new style classes

Peter Otten __peter__ at web.de
Wed Jul 6 12:40:48 EDT 2005


Thomas Heller wrote:

> I'm trying to implement __iter__ on an abstract base class while I don't
> know whether subclasses support that or not.
> Hope that makes sense, if not, this code should be clearer:
> 
> class Base:
>     def __getattr__(self, name):
>         if name == "__iter__" and hasattr(self, "Iterator"):
>             return self.Iterator
>         raise AttributeError, name
 
> Is there any way I could make the above code work with new style
> classes?

Obligatory metaclass approach:

class Base:
    class __metaclass__(type):
        def __new__(mcl, name, bases, classdict):
            try:
                classdict["__iter__"] = classdict["Iterator"]
            except KeyError:
                pass
            return type.__new__(mcl, name, bases, classdict)

class Alpha(Base):
    def Iterator(self): yield 42

class Beta(Base):
    def __getitem__(self, index):
        return [1, 2, 3, "ganz viele"][index]


for item in Alpha(): print item
for item in Beta(): print item,
print

Peter




More information about the Python-list mailing list