Python function as a function argument? Python function as a function argument? python python

Python function as a function argument?


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


Here's another way using *args (and also optionally), **kwargs:

def a(x, y):  print x, ydef b(other, function, *args, **kwargs):  function(*args, **kwargs)  print otherb('world', a, 'hello', 'dude')

Output

hello dudeworld

Note that function, *args, **kwargs have to be in that order and have to be the last arguments to the function calling the function.


Functions in Python are first-class objects. But your function definition is a bit off.

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