Functions as Arguments
Learn how to pass functions as parameters, significantly enhancing code reusability and efficiency in software development.
We'll cover the following...
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 thecalculator
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
andn2
, will hold the values that will be passed tooperation
.Line 14: The
multiply
function and the values10
and20
are passed to the calculator function. The result200
is saved to a variableresult
and displayed.Lines 17–18: The
add
function and the values10
and20
are passed to the calculator function. The result30
is directly passed to theprint
function and displayed.Lines 21–22: Here we see that the
subtract
function is first stored in a variablesub_var
and then passed to thecalculator
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.
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))