Recursive generator

Ben C spamspam at spam.eggs
Tue Feb 12 06:15:28 EST 2008


Suppose I have an object containing an array called children. I can
therefore build a tree out of such objects.

I thought it might be useful to have a descendent generator, so I could
write:

    for thing in self.genDescendents():
        foo(thing)

expecting foo to be called for each descendent in pre-order.

The best I came up with so far is :

    def genDescendents(self):
        for child in self.children:
            yield child
            for grandChild in child.genDescendents():
                yield grandChild

I think this works OK, but it seems a bit odd. Is there something more
"Pythonic" I should be doing?



More information about the Python-list mailing list