Mixing generators and recursion

Peter Otten __peter__ at web.de
Tue Nov 4 15:36:39 EST 2003


Gerson Kurz wrote:

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

You are creating a generator here, but never use it. Change the above line
to
           
              for subpn in walkem(pathname):
                  yield subpn  
>             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?

Calling a generator just creates it. Invoke the next() method to draw the
actual items (the for loop does this implicitely).
Sometimes it may be instructive to have a look at the library code: in your
case os.walk() may be worth investigating since it performs a similar task.

Peter




More information about the Python-list mailing list