Home > Net >  Add a function as a parameter in Python
Add a function as a parameter in Python

Time:12-22

Imagine that I want to create a function called "execute()". This function takes the name of another function and its input as parameters and outputs whatever it returns.

Here is an example:

execute(print, "Hello, World!") # "Hello, World!"
execute(str, 68) # "68"

Of course, this function wouldn't be of any use, but I want to grasp the main idea of putting another function in as a parameter. How could I do this?

CodePudding user response:

You can just do this,

def execute (func, argv):
    return func(argv)
execute(print, 'test')

returns test

execute(str, 65)

returns '65'

CodePudding user response:

Functions can easily be passed into functions. To pass a variable length argument list, capture it with *args in the function definition and when calling the func use the same syntax to expand the arguments again into multiple parameters.

def execute(fn, *args):
  return fn(*args)

Note: we are not passing the name of a function to execute(), we are passing the function itself.

CodePudding user response:

I believe this should work:

def execute(fn, *args, **kwargs):
    return fn(*args, **kwargs)

Here:

  • args = Arguments (list)
  • kwargs = Keyworded Arguments (dictionary)

If you want to do more, then you can look for Decorators in Python.

CodePudding user response:

Yes, you can pass functions as parameters into another function. Functions that can accept other functions as arguments are also called higher-order functions. I hope the following example helps:

def shout(text): 
    return text.upper() 

def greet(func):
   greeting = func("Hi, I am created by a function passed as an argument.") 
   print(greeting)

greet(shout) 

The output of the code will be :

HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.

  • Related