Recursive Generator Question

Brian McErlean b_mcerlean at yahoo.com
Fri Sep 3 11:45:03 CEST 2004


pchiusan at umich.edu (Paul Chiusano) wrote in message news:<6543373d.0409021839.5caff11d at posting.google.com>...
> I've been playing around with generators and have run into a
> difficulty. Suppose I've defined a Node class like so:
> 
> class Node:	
> 	def __init__(self, data=None, left=None, right=None):
> 		self.children = []
> 		self.children.append(left)
> 		self.children.append(right)
> 		self.data = data
> 	
> 	def __iter__(self): return self
> 			
> 	def next(self):
>         """ Returns iteration over terminal nodes of this tree. """
> 		if self.data:
> 			yield self
> 		else:
> 			for child in self.children:
> 				for terminal in child:
> 					yield terminal
> 

[ ... ]

> For some reason, that iteration is returning generators instead of
> leaves. Curiously, if I replace that for loop with

This is because you told it to.  The next() method needs to return the
single next element, but the one above is returning a generator, so
you end up with a sequence of generators.  If you make the object its
own iterator (returning self in __iter__), you will have to save some
state to remember what position you are at (which is bad since it
prevents multiple iterators)

What you probably meant to do is to put the code in the next() method
directly in __iter__ - that way the generator returned is your
iterator, rather than the object itself.

Brian.



More information about the Python-list mailing list