Python function as a function argument?

a7664 picture a7664 · Jun 9, 2011 · Viewed 203.8k times · Source

Can a Python function be an argument of another function?

Say:

def myfunc(anotherfunc, extraArgs):
    # run anotherfunc and also pass the values from extraArgs to it
    pass

So this is basically two questions:

  1. Is it allowed at all?
  2. And if it is, how do I use the function inside the other function? Would I need to use exec(), eval() or something like that? Never needed to mess with them.

BTW, extraArgs is a list/tuple of anotherfunc's arguments.

Answer

Manuel Salvadores picture Manuel Salvadores · Jun 9, 2011

Can a Python function be an argument of another function?

Yes.

def myfunc(anotherfunc, extraArgs):
    anotherfunc(*extraArgs)

To be more specific ... with various arguments ...

>>> def x(a,b):
...     print "param 1 %s param 2 %s"%(a,b)
...
>>> def y(z,t):
...     z(*t)
...
>>> y(x,("hello","manuel"))
param 1 hello param 2 manuel
>>>