1

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?

  • In python everything is an object, so it can be passed as an argument to a function. There is a nice lecture about [functions being first class objects in python](https://realpython.com/lessons/functions-first-class-objects-python) on real python. I suggest you check it out! – j-i-l Dec 21 '21 at 10:05

4 Answers4

0

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.

vaizki
  • 1,678
  • 1
  • 9
  • 12
  • Thank you! Stackoverflow says that I can accept your answer in 10 minutes. –  Dec 21 '21 at 10:02
0

You can just do this,

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

returns test

execute(str, 65)

returns '65'

anarchy
  • 3,709
  • 2
  • 16
  • 48
0

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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Gagan Deep Singh
  • 372
  • 3
  • 13
  • What is the difference between *args and **kwargs (I mean the * and the **)? –  Dec 27 '21 at 23:19
-1

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.

Adii_Mathur
  • 307
  • 2
  • 7