Python: Functions
Theory: Higher-order functions
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:
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:
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:
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.