Recursive Generator Question

Tim Peters tim.peters at gmail.com
Fri Sep 3 06:09:18 CEST 2004


[Dan Christensen]
...
>    def __iter__(self): 
>        if self.data != None:
>            yield self.data
>        for child in self.children:
>            if child != None:
>                for terminal in child:
>                    yield terminal

...

> To the experts:  I don't recall seeing __iter__ be a generator like
> this before.  How would you code it?

The way you did.  A generator *is* a (one kind of) iterator, so it's
fine to use a generator anywhere an iterator is desired. 
(Technically, the __iter__ method there is called a
generator-function, and the thing it returns is called a
generator-iterator.)



More information about the Python-list mailing list