A simple generator application

Oren Tirosh oren-py-l at hishome.net
Sun Oct 13 09:46:28 EDT 2002


On Sat, Oct 12, 2002 at 05:22:40PM +0000, Doug Fort wrote:
> def dirWalker(top):
>     """
>     a generator that walks a directory tree
> 
>     This code is based on os.path.walk, with the callback function
>     replaced by a yield and recursion replaced by crude iteration
>     """
>     dirstack = [top]
>     while len(dirstack) > 0:
...

Why remove the recursion? It's the easiest way to write this code. I find
it much more straightforward than maintaining an explicit stack.

Recursive generators are a fantastic tool. They combine the power of
recusion with a simple, "linear" output format.  They're also quite 
efficient because yielding a value is almost an order of magnitude faster 
than calling a Python function. Unless your recursion is really deep 
yielding the values up the chain is not going to cause any significant 
overheads.

	Oren




More information about the Python-list mailing list