[Tutor] Passing Functions or Code as Parameters

Kent Johnson kent37 at tds.net
Thu Oct 27 18:33:48 CEST 2005

Ed Singleton wrote:
> Wow, thanks again, Kent.
> If my understanding of functions in Python is correct, then the
> do_something() function won't have access to the variables inside
> traverse.  Is this right?

Yes, that's right. Python is lexically scoped which means you have access to variables in the enclosing scopes in the actual program text, not the scope of the callers.
> I know I could pass them as parameters:
> def traverse(directory, things_to_do, depth=0):
>     thedir = path(directory)
>     for item in thedir.files():
>          things_to_do(depth, item)
>     for item in thedir.dirs():
>         traverse(item, things_to_do, depth+1)
> But what if I don't know in advance what parameters I want to pass? 

You don't have very many possibilities here, maybe just pass them all? You could pass locals() to things_to_do() - locals() returns a dictionary containing all the current local variables. Then things_to_do() would take a single argument and extract the variables it wants.

Why do you need this much flexibility? I would just pass thedir, item and depth to things_to_do().

> Can I pass a block of code that will be executed within the function's
> scope?

Yes, you can define a function within traverse() and pass that function to things_to_do(), but I don't know how that will help.


PS Please reply on list so others can participate.

More information about the Tutor mailing list