Higher Order Functions and decorators in Python

Higher Order Functions:

Higher Order Functions (HOFs) are functions that express complex concepts by combining simpler functions into a new function. It is a function that contains a function as parameter and returns another function as a result.

Properties of Higher Order Functions:

  1. We can store a function inside a variable.
  2. A function can act as instance of an object
  3. We can pass a function as an argument to another function
  4. We can store Python higher order functions in data structures such as list, hash tables etc.,

Functions as object:

               In Python, a function can be assigned to a variable. Here, a reference to the function is created.

Example:

Passing Function as an argument to another function:

Functions are like objects in Python, so they can be passed as an argument to another function.

Returning Function:

As functions are objects, we can also return a function from another function.

Decorators as Higher Order Function:

               We can use decorators as higher order function. Decorators in Python allow us to extend behavior of methods or functions without explicitly modifying it.

Decorators allow us to wrap another function to extend the behavior of wrapped function, without modifying it.

Syntax:

# Using a decorator  

@myDecorator  

def Python_Decorator():   

.

.

The above decorator syntax is equivalent to the below syntax for using decorator as higher order function in python.

def Python_Decorator():   

    .  

    .  

Python_Decorator = @myDecorator(Python_Decorator)  

Example:

In the next article we will see about map(), reduce() and filter() higher order functions.