programmatically calling a function

Peter Hansen peter at engcorp.com
Sat Mar 5 03:37:02 CET 2005


Dave Ekhaus wrote:
>     i'd like to call a python function programmatically - when all i 
> have is the functions name as a string.  i.e.
 >
> fnames = ['foo', 'bar']

The usual answer at this point is to say that functions are
"first class objects" in Python, which basically means you
can haul around references to them instead of having to
refer to them indirectly with strings.  This isn't always
possible, but see if this might be something you can do instead:

  funcs = [foo, bar]  # note: no quotation marks!

  for func in funcs:
      func(1, 2, 3)	# call each function, passing three arguments...

> for func in fnames:
>     # how do i call function 'func' when all i have is the name of the 
> function ???

To convert from the name to a reference, you'll still need access
to the functions, so often you don't really need to use the names
approach.  Still, if you must, all you need to know is what namespace
the functions are defined in.  If they're local to the current module,
you can use globals(), which returns a dictionary of global names
that you can index using the name:

fnames = ['foo', 'bar']
for name in fnames:
     func = globals()[name]
     func(1, 2, 3)	# call function with three arguments, or whatever


-Peter



More information about the Python-list mailing list