Conditionally implementing __iter__ in new style classes

Delaney, Timothy (Tim) tdelaney at avaya.com
Wed Jul 6 19:37:37 EDT 2005


Thomas Heller wrote:

> 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.

Again, why not just let subclasses implement __iter__? Calling iter() on
an instance of the base class (or any subclass that does not implement
__iter__) will return an iterator that uses __getitem__. Calling iter()
on a subclass instance that does implement __iter__ will return the
iterator from the subclass __iter__.

Tim Delaney



More information about the Python-list mailing list