[Python-Dev] metaclass insanity

Aahz aahz@pythoncraft.com
Tue, 5 Nov 2002 10:13:33 -0500

On Tue, Nov 05, 2002, Just van Rossum wrote:
> Just van Rossum wrote:
>> class Outer:
>>     [snip snip]
>>     def __iter__(self):
>>         while not self.isAtEnd():
>>             result = self.outer.currentState()
>>             self.outer.advanceState()
>>             yield result
> PS, getting more off-topic, I'm somewhat surprised that the above is more
> compact and readable than the obvious generator-less equivalent:
> class Outer:
>     [snip snip]
>     def __iter__(self):
>         return self
>     def next(self):
>         if self.isAtEnd():
>             raise StopIteration
>         else:
>             result = self.outer.currentState()
>             self.outer.advanceState()
>             return result

Hmmmm...  I'm surprised that you're surprised.  Here's my slide from

Generators simpler 
    No need to explicitly maintain state 

Iterators more controllable 
    Can manipulate internal state (e.g., __del__ method on iterator
    object to handle cleanup)

    Can be backported to older versions of Python

Generally speaking, I can think of few reasons to build an actual
iterator class rather than a generator.
Aahz (aahz@pythoncraft.com)           <*>         http://www.pythoncraft.com/

Project Vote Smart: http://www.vote-smart.org/