Here’s another article in the Functions in Python series. Today we’ll learn how to pass functions as parameters. If you haven’t read the previous parts yet, feel free to do so. Here they are:
6) Mutable Optional Parameters
8) Arbitrary Number of Positional Parameters
9) Arbitrary Number of Keyword Parameters
10) Arbitrary Number of Both Positional and Keyword Parameters
11) Nested Functions
12) Calling Functions in Other Functions
13) Assigning Functions to Variables
Functions are first-class objects, which means they are objects like any other objects, which further means they can be used just like other objects. Translating this into plain English, we can assign functions to variables and pass them as arguments to other functions. They can also be returned from other functions. If you want to read more about functions as first-class objects, I have an article about that.
And now let’s talk about passing functions as parameters.
Parameters are references to objects. These can be objects of any kind. Functions are objects as well, so they can be passed as parameters too. Here we have two simple functions. The first one is not extremely useful, it just prints the message “The end”. The second function takes two parameters. The first one is a number that will be squared and the second is a function which will be called inside the square function. With the functions defined, we’ll call the second of them with the arguments 5 and write_the_end. Now the square function will square the number 5 and output it as a formatted string and then it’ll call the write_the_end function which will print the “The end” message:
def write_the_end():
print("The end")
def square(x, func):
print(f"{x} ^ 2 = {x ** 2}")
func()
square(5, write_the_end)
And here’s what we get when we run the program:
5 ^ 2 = 25
The end
If needed, you can access the name of the function passed as parameter in the calling function. In order to do that you should use the __name__ variable:
def write_the_end():
print("The end")
def square(x, func):
print(f"{x} ^ 2 = {x ** 2}")
print(f"The following message is produced by the {func.__name__} function.")
print("And here's the message:")
print()
func()
square(5, write_the_end)
Now we have the name of the function in the output:
5 ^ 2 = 25
The following message is produced by the write_the_end() function.
And here's the message:
The end
Function with Parameters Passed As Argument
Next we have an example of a function that takes parameters and is itself passed as a parameter to another function:
def add_numbers(a, b):
return a + b
def add_ten(x, func):
return func(x, 10)
print(add_ten(17, add_numbers))
And here’s the output:
27