Style question on recursive generators

Stefan Behnel behnel_ml at dvs1.informatik.tu-darmstadt.de
Mon Oct 18 11:42:15 EDT 2004


Carlos Ribeiro schrieb:
> def walk(self):
>    """generator-based recursive tree traversal"""
>    yield child
>    for child in childs:
>         transfer child.walk()
> 
> It's quite weird -- a generator plus a direct flow-of-execution
> transfer. It's not a goto, its not a co-routine... It requires a new
> keyword ('transfer', in this case), which _is_ a real problem --
> something like this can't be lightly proposed. In this case, it's just
> a thought experiment, at this point; nothing serious, and far from a
> proposal.


I know what it feels like. I had to implement the same thing for a 
recursive parser once - looks somewhat inefficient to iterate over a 
iterator only for yielding the iterator's results...

Maybe you know the itertools module?

http://www.python.org/dev/doc/devel/lib/itertools-functions.html

It has some nice functions that can make this sort of code more readable 
(and maybe even more efficient). You may find itertoold.chain especially 
useful.

Stefan



More information about the Python-list mailing list