Conditionally implementing __iter__ in new style classes

Dieter Maurer dieter at handshake.de
Thu Jul 7 14:25:05 EDT 2005


Thomas Heller <theller at python.net> writes on Wed, 06 Jul 2005 18:07:10 +0200:
> Thomas Heller <theller at python.net> writes:
> ...
> > class Base:
> >     def __getattr__(self, name):
> >         if name == "__iter__" and hasattr(self, "Iterator"):
> >             return self.Iterator
> >         raise AttributeError, name
> >
> > class Concrete(Base):
> >     def Iterator(self):
> >         yield 1
> ...
> > If, however, I make Base a newstyle class, this will not work any
> > longer.  __getattr__ is never called for "__iter__" (neither is
> > __getattribute__, btw).  Probably this has to do with data descriptors
> > and non-data descriptors, but I'm too tired at the moment to think
> > further about this.
> >
> > Is there any way I could make the above code work with new style
> > classes?
> 
> I forgot to mention this: The Base class also implements a __getitem__
> method which should be used for iteration if the .Iterator method in the
> subclass is not available.  So it seems impossible to raise an exception
> in the __iter__ method if .Iterator is not found - __iter__ MUST return
> an iterator if present.

Then, it should return an interator (a new object) that uses
the "__getitem__" method to iterate.


Dieter



More information about the Python-list mailing list