In Python, everything is an object. It means that everything can be transmitted and received by reference. The same applies to functions.
In languages where functions can be taken and passed as values, functions are first-class citizens. In Python, we refer to functions that take other functions as arguments or return functions as higher-order functions.
First-order functions accept and return regular values, not functions. Let us implement it:
def call_with_five(function):
return function(5)
def add_one(x):
return x + 1
call_with_five(add_one)
# 6
The call_with_five
takes another function at the input and returns the result of its call with the argument 5
. To complicate the example, we will also add what the function returns:
def double(function):
def inner(argument):
return function(function(argument))
return inner
def multiply_by_five(x):
return x * 5
double(multiply_by_five)(3)
# 75
In this example, the inner
function is created in the body of the double
and returned as a result. This name often shows functions created on the fly inside external ones.
Since calling double
returns a function, we can immediately make a second call (3)
, which will give us the result of applying the original one to the argument twice. But we could not call the value function immediately. Instead, we saved it to a variable:
multiply_by_25 = double(multiply_by_five)
multiply_by_25
# <function double.<locals>.inner at 0x7fd1975c58c8>
multiply_by_25(1)
# 25
multiply_by_625 = double(multiply_by_25)
multiply_by_625
# <function double.<locals>.inner at 0x7fd1968f41e0>
multiply_by_625(1)
# 625
Note that when displaying the reference value multiply_by_25
, we see double'.<locals>.inner
. It is the inner
function created on the fly.
The function is called inner
in the case of multiply_by_625
, but the address is different — a hexadecimal number after at
.
Now it may seem to you that the examples above are rather far-fetched and do not look like real-life code. However, do not rush to conclusions. Higher-order functions are a powerful tool in the right hands. In the next lesson, we will look at several higher-order functions, which are from a practical point of view.
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.