Recursive Generators in Python 2 and 3
Generators decouple iteration from the code that uses the results of the iteration.
—David Beazley, Generators
[Previously published at the now defunct MetaBrite Dev Blog.]
Python generators have a variety of uses. One such is to lazily evaluate sequences. Another is for coroutines. Yet another is to recursively traverse a tree or a graph, yielding an iterable sequence.
Consider this simple tree of nodes:
node_tree = Node( 'a', [ Node('b', [ Node('e', [ Node('g')…continue.