Mixing generators and recursion

Gerson Kurz gerson.kurz at t-online.de
Tue Nov 4 15:21:27 EST 2003


I stumbled upon a behaviour that would be somewhat nice to have, but
seemingly is not possible (in 2.3 anyway):

import os, stat 

def walkem(directory):
    print "Read files in %s" % directory
    for filename in os.listdir(directory):
        pathname = os.path.join(directory, filename)
        if os.path.isdir(pathname):
            print "Before walkem: %s" % pathname
            walkem(pathname)
            print "After walkem: %s" % pathname
        else:
            yield pathname
    
if __name__ == "__main__":
    for filename in walkem("<your directory here>"):
        print filename

This code will not recurse subdirectories - because the recursive
walkem() is not called (or so is my interpretation). It is of course
easy to rewrite this; I was just wondering if someone can enlighten me
why this happens (the yield documentation doesn't give me any clues),
and whether this might be a future feature?


        





More information about the Python-list mailing list