...

/

Functions as Arguments

Functions as Arguments

Learn how to pass functions as parameters, significantly enhancing code reusability and efficiency in software development.

In Python, one function can become an argument for another function. This is useful in many cases. Let’s make a calculator function that requires the add, subtract, or multiply function along with two numbers as arguments. For this, we’ll have to define the three arithmetic functions as well.

Using simple functions

In this example, we have several functions for basic arithmetic operations and a calculator function that takes another function as its argument to perform the specified operation.

Press + to interact
def add(n1, n2):
return n1 + n2
def subtract(n1, n2):
return n1 - n2
def multiply(n1, n2):
return n1 * n2
def calculator(operation, n1, n2):
return operation(n1, n2) # Using the 'operation' argument as a function
# Using the calculator with the multiply function
print(calculator(multiply, 10, 20))
# Using the calculator with the add function
result = calculator(add, 5, 3)
print(result)
# Assigning a function to a variable and passing it to the calculator
sub_var = subtract
print(calculator(sub_var, 10, 20))

Explanation

Here’s the code explanation:

  • Lines 1–8: Here we see the three functions, add, subtract, and multiply. These will be passed as arguments to the calculator function.

  • Lines 10–11: The calculator function is declared here. It's first parameter, operation, will hold the function that needs to be executed. The next two parameters, n1 and n2, will hold the values that will be passed to operation.

  • Line 14: The multiply function and the values 10 and 20 are passed to the calculator function. The result 200 is saved to a variable result and displayed.

  • Lines 17–18: The add function and the values 10 and 20 are passed to the calculator function. The result 30 is directly passed to the print function and displayed.

  • Lines 21–22: Here we see that the subtract function is first stored in a variable sub_var and then passed to the calculator function.

Using lambdas for readability

For the calculator method, we needed to write three extra functions that could be used as the argument. This can be quite a hassle. Why don’t we just pass a lambda as the argument? The operations are pretty simple, so they can be written as lambdas. Let’s try it.

Press + to interact
def calculator(operation, n1, n2):
return operation(n1, n2) # Using the 'operation' argument as a function
# 10 and 20 are the arguments.
result = calculator(lambda n1, n2: n1 * n2, 10, 20)
# The lambda multiplies them.
print(result)
print(calculator(lambda n1, n2: n1 + n2, 10, 20))
...