Turning f(callback) into a generator

Diez B. Roggisch deets_noospaam at web.de
Wed Dec 3 21:50:10 CET 2003


Hi,

> 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?

This works for me:

import os.path

def path_gen(start):
    res = []
    def cb(r, dir, names):
        for n in names:
            r.append(n)

    os.path.walk(start, cb, res)
    for n in res:
        yield n


g = path_gen("/etc")

for n in g:
    print n


Diez




More information about the Python-list mailing list