Turning f(callback) into a generator

Bengt Richter bokr at oz.net
Wed Dec 3 17:41:38 EST 2003


On Wed, 03 Dec 2003 18:48:41 +0100, Peter Otten <__peter__ at web.de> wrote:

>It's easy to write a function that wraps a generator and provides a
>callback. E. g.:
>
>import os, sys
>
>def walk(path, visit):
>    """ Emulate os.path.walk() (simplified) using os.walk()"""
>    for dir, folders, files in os.walk(path):
>        visit(dir, folders + files)
>
>
>if __name__ == "__main__":
>    walk(".", lambda d, f: sys.stdout.write(d + "\n"))
>
>
>However, I did not succeed in turning the old os.path.walk(), i. e. a
>function taking a callback, into a generator. Is there a general way to do
>it without having to store all intermediate results first?
>
>
>Peter
>
>PS. No, I don't have a use case. Threads welcome if all else fails :-)
>
I suspect that's what is necessary currently, until we get a yield that can suspend a
whole stack of frames at a yield inside nested calls to functions. Then it would
just be a matter of putting a yield in a callback routine and starting the
walk from the base generator-making function/method/whatever.

Maybe deep generators could be created via an __iter__ method of the function type
as an alternative/extension to has-yield-in-function-code-body magic.
Exit from the generator wouldn't happen until you exited the base frame.
Yield in a nested function call would just suspend right there.
Easier said than done, of course ;-)

Regards,
Bengt Richter




More information about the Python-list mailing list