[Tutor] Passing Functions or Code as Parameters

Ed Singleton singletoned at gmail.com
Thu Oct 27 15:01:47 CEST 2005


How can I pass a block of code to a function for it to perform within itself?

For example, I wrote a small function that recurses through a
directory structure but keeps a track of the depth:

from path import path

def traverse(directory, depth=0):
    thedir = path(directory)
    for item in thedir.files():
##      Do stuff relative to the depth
    for item in thedir.dirs():
        traverse(item,depth+1)

What I want to do is something like:

from path import path

def traverse(directory, depth=0, things_to_do()):
    thedir = path(directory)
    for item in thedir.files():
        things_to_do(depth)
    for item in thedir.dirs():
        traverse(item,depth+1)

Is this possible?

Thanks

Ed


More information about the Tutor mailing list