Higher Order Functions in Python
A function is called Higher Order Function if it contains other functions as a parameter or returns a function as an output i.e, the functions that operate with another function are known as Higher order Functions. It is worth knowing that this higher order function is applicable for functions and methods as well that takes functions as a parameter or returns a function as a result. Python too supports the concepts of higher order functions.
Properties of higher-order functions:
- A function is an instance of the Object type.
- You can store the function in a variable.
- You can pass the function as a parameter to another function.
- You can return the function from a function.
- You can store them in data structures such as hash tables, lists, …
Functions as objects
In Python, a function can be assigned to a variable. This assignment does not call the function, instead a reference to that function is created. Consider the below example, for better understanding.
In the above example, a function object referenced by shout and creates a second name pointing to it, yell.
Passing Function as an argument to other function
Functions are like objects in Python, therefore, they can be passed as argument to other functions. Consider the below example, where we have created a function greet which takes a function as an argument.
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT. hi, i am created by a function passed as an argument.
As functions are objects, we can also return a function from another function. In the below example, the create_adder function returns adder function.
Decorators are the most common use of higher-order functions in Python. It allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of wrapped function, without permanently modifying it. In Decorators, functions are taken as the argument into another function and then called inside the wrapper function.
@gfg_decorator def hello_decorator(): . . .
The above code is equivalent to –
def hello_decorator(): . . . hello_decorator = gfg_decorator(hello_decorator)
In the above code,
gfg_decorator is a callable function, will add some code on the top of some another callable function,
hello_decorator function and return the wrapper function.
Hello, this is before function execution This is inside the function !! This is after function execution
Note: For more information, refer to Decorators in Python.