Recursive Generator Question

Dan Perl dperl at rogers.com
Fri Sep 3 00:11:18 EDT 2004


"Jp Calderone" <exarkun at divmod.com> wrote in message
news:mailman.2804.1094182395.5135.python-list at python.org...
> Paul Chiusano wrote:
       .........
>    The generators are a red herring :)  Iterating over an object calls
> __iter__ on the object, then repeatedly calls next on the object
> returned by __iter__.  Each object next returns is taken as a value for
> iteration.
>
>    So, if we examine your node class, we see that when __iter__ is
> called, the same object is returned.  When next is called on the node
> class, a generator is returned.  Oops.  Throw away your current __iter__
> method and rename your next method __iter__.  Now when __iter__ is
> called, it will return a generator, and when next is called on the
> generator, you will get the leaf nodes you were looking for.

I think a clarification is in order here.  Done this way, __iter__ *IS* a
generator function and it returns an iterator, not a generator.  The next( )
is called on the iterator returned by __iter__.  Using __iter__ as the
generator takes advantage of the fact that the 'for' statement invokes it
implicitly.  But the generator could have any name and it would just have to
be called explicitly.

I would rather do it the explicit way, and it's not just because I'm
following the advice I've been getting from a lot of people in another
thread, where I was on the 'implicit' side of the argument.   ;-)

But this way, the 'implicit' call to __iter__, works too.

Dan





More information about the Python-list mailing list