[python] Python function as a function argument?

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.

This question is related to python function arguments

The answer is


Sure, that is why python implements the following methods where the first parameter is a function:

  • map(function, iterable, ...) - Apply function to every item of iterable and return a list of the results.
  • filter(function, iterable) - Construct a list from those elements of iterable for which function returns true.
  • reduce(function, iterable[,initializer]) - Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.
  • lambdas

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

def a(x, y):
  print x, y

def b(other, function, *args, **kwargs):
  function(*args, **kwargs)
  print other

b('world', a, 'hello', 'dude')

Output

hello dude
world

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


def x(a):
    print(a)
    return a

def y(func_to_run, a):
    return func_to_run(a)

y(x, 1)

That I think would be a more proper sample. Now what I wonder is if there is a way to code the function to use within the argument submission to another function. I believe there is in C++, but in Python I am not sure.


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

Function inside function: we can use the function as parameter too..

In other words, we can say an output of a function is also a reference for an object, see below how the output of inner function is referencing to the outside function like below..

def out_func(a):

  def in_func(b):
       print(a + b + b + 3)
  return in_func

obj = out_func(1)
print(obj(5))

the result will be.. 14

Hope this helps.


Decorators are very powerful in Python since it allows programmers to pass function as argument and can also define function inside another function.

def decorator(func):
      def insideFunction():
        print("This is inside function before execution")
        func()
      return insideFunction

def func():
    print("I am argument function")

func_obj = decorator(func) 
func_obj()

Output

  • This is inside function before execution
  • I am argument function

def x(a):
    print(a)
    return a

def y(a):
    return a

y(x(1))

  1. Yes. By including the function call in your input argument/s, you can call two (or more) functions at once.

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!


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

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

  1. Yes, it's allowed.
  2. You use the function as you would any other: anotherfunc(*extraArgs)

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to arguments

docker build with --build-arg with multiple arguments ARG or ENV, which one to use in this case? How to have multiple conditions for one if statement in python Gradle task - pass arguments to Java application Angularjs - Pass argument to directive TypeError: method() takes 1 positional argument but 2 were given Best way to check function arguments? "Actual or formal argument lists differs in length" Python: Passing variables between functions Print multiple arguments in Python