Turning f(callback) into a generator

Peter Otten __peter__ at web.de
Wed Dec 3 12:48:41 EST 2003


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 :-)





More information about the Python-list mailing list