Recursive generator

Erich sophacles at gmail.com
Wed Feb 13 17:01:54 EST 2008


On Feb 12, 5:15 am, Ben C <spams... at spam.eggs> wrote:
> I think this works OK, but it seems a bit odd. Is there something more
> "Pythonic" I should be doing?

I have a similar tree to the one you describe here at work. I have a
visit function that is very similar to yours, but takes function
arguments for doing pre- and/or post- order operations on the node
(code below). It also yeilds the nodes, but in a postorder manner. The
flexibility is quite useful.

Regards,
Erich

    def visit(self,prefunc = None, postfunc = None):
        if prefunc:
            prefunc(self)

        for child in self.children:
            for y in child.visit(prefunc, postfunc):
                yield y

        if postfunc:
            postfunc(self)

        yield self



More information about the Python-list mailing list