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.
def add(n1, n2):return n1 + n2def subtract(n1, n2):return n1 - n2def multiply(n1, n2):return n1 * n2def calculator(operation, n1, n2):return operation(n1, n2) # Using the 'operation' argument as a function# Using the calculator with the multiply functionprint(calculator(multiply, 10, 20))# Using the calculator with the add functionresult = calculator(add, 5, 3)print(result)# Assigning a function to a variable and passing it to the calculatorsub_var = subtractprint(calculator(sub_var, 10, 20))
Explanation
Here’s the code explanation:
Lines 1–8: Here we see the three functions,
add,subtract, andmultiply. These will be passed as arguments to thecalculatorfunction.Lines 10–11: The
calculatorfunction is declared here. It's first parameter,operation, will hold the function that needs to be executed. The next two parameters,n1andn2, will hold the values that will be passed tooperation.Line 14: The
multiplyfunction and the values10and20are passed to the calculator function. The result200is saved to a variableresultand displayed.Lines 17–18: The
addfunction and the values5and3are passed to the calculator function. The result8is directly passed to theprintfunction and displayed.Lines 21–22: Here we see that the
subtractfunction is first stored in a variablesub_varand then passed to thecalculatorfunction.
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.
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))