Style question on recursive generators

Daniel Dittmar daniel.dittmar at sap.corp
Mon Oct 18 08:11:53 EDT 2004


Carlos Ribeiro wrote:
> Hello all,
> 
> Here I am using some deeply nested, tree-like data structures. In some
> situations I need to traverse the tree; the old-style way to do it is
> to write a recursive method on the node class, as in:
> 
> def walk(self):
>     """old-style recursive tree traversal"""
>     child.do_something
>     for child in childs:
>         child.walk()
> 
[...]
> 
> def walk(self):
>     """generator-based recursive tree traversal"""
>     yield child
>     for child in childs:
>         for node in child.walk()
>             yield node
> 
[...]
> I'm now wondering which is better: to keep using old-style recursive
> tree traversal code, or to chained-yield generator solution. It's more
> of a stylistic decision -- I'm not concerned about raw performance at
> this point, but clarity and elegancy of design are more important.
> 

You must also consider the code that uses the iteration, at least if you 
want to walk the structure for multiple purposes

# In the recursive case
def nodeHandler (node):
     node.do_something ()

root.walk (nodeHandler)

# in the generator case
for node in root.walk ():
     node.do_something ()

And the latter can also be fed into routines that expect an iterator.

Compare also os.path.walk with os.walk.

Daniel



More information about the Python-list mailing list