Python Decorators [Part 3]

Higher Order Decorators

Sumeet Sarkar
1 min readNov 24, 2018

Python decorators [Part 2] we learnt about nested decorators, here we understand what is higher order decorators

Simply said, Higher Order Decorators are decorators with arguments.

Why do we need it?

Let us take the doubleit example again for reference. Can we extend our use case from double to triple, etc or any number? Can we have a generic implementation? First we will try working it out with closures once again.

The magic function returns a wrapper, which again returns a wrapper function. In effect, we are parameterising even the multiplier to be used to multiply a number we pass on later.

wrapper1 takes the mul function and returns a function wrapper2.

wrapper2 is invoked with a number, and calls the actual mul function with the multiplier and number.

As we have already learnt about decorators acting as syntactical replacements for statements like times5 = magic(mul)(5)

We can pass parameters to decorators just like regular functions.

Here, the same thing happens using the decorator syntax.

@times(5) invokes the function times with multiplier 5 and returns wrapper1

wrapper1 takes in the mul function and returns wrapper2

wrapper2 when invoked with a number, simply calls mul function with the multiplier and number

Higher Order Decorators return decorators

In the Python decorators [Part 4] article, we will talk about Decorators as Classes

Python decorator series

Python decorators [Part 1]
Python decorators [Part 2]
Python decorators [Part 3]
Python decorators [Part 4]

--

--

Sumeet Sarkar

All things Javascript & Python. Love problem solving. I am also a photographer, foodie, impatient, philosophical. Engineering @ Postman