Python function as function argument?

Can a Python function be an argument to another function?

Say:

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

So these are basically two questions:

  • Is it allowed at all?
  • And if so, how can I use a function inside another function? Should I use exec (), eval () or something like that? You never had to mess with them.

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

+61
function python arguments
Jun 09 2018-11-11T00:
source share
6 answers

Can a Python function be an argument to another function?

Yes.

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

More specifically ... 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 >>> 
+67
Jun 09 2018-11-11T00:
source share

All of the above examples lead to TypeErrors if your def uses *args (and optionally) **kwargs for a function that calls another function:

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

Exit

 hello dude world 

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

+17
Sep 16 '15 at 21:01
source share

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

 def myfunc(anotherfunc, extraArgs, extraKwArgs): return anotherfunc(*extraArgs, **extraKwArgs) 
+15
Jun 09 '11 at 7:50
source share

Of course, therefore, python implements the following methods, where the first parameter is a function:

  • map (function, iterable, ...) - apply a function to each iterable element and return a list of results.
  • filter (function, iterable) - create a list of these iteration elements for which the function returns true.
  • reduce (function, iteration [, initializer]) - apply the function two arguments cumulatively refer to iteration points, from left to right, to reduce the iteration value to one value.
  • lambdas
+3
Jun 09 2018-11-11T00:
source share
  • Yes, it is allowed.
  • You use this function like any other: anotherfunc(*extraArgs)
+2
Jun 09 2018-11-11T00:
source share
  • Yes. By including a function call in your / s input argument, you can call two (or more) functions at the same time.

For example:

 def anotherfunc(inputarg1, inputarg2): pass def myfunc(func = anotherfunc): print func 

When you call myfunc, you do this:

 myfunc(anotherfunc(inputarg1, inputarg2)) 

This will print the return value of anotherfunc.

Hope this helps!

+2
May 17 '14 at 7:02
source share



All Articles