Python Decorators [Part 2]

Nested Decorators

Sumeet Sarkar
2 min readNov 13, 2018

A function can have a decorator, which in turn can be decorated by another decorator. And hence, a nested decorator.

In simple words, a decorator modifies the intent of a function, and a nested decorator, modifies the already modified function.

Order of decorators in nested decorators MATTERS

Output:begin executing fn: greet ----
Hello World
-----end fn: greet
begin executing fn: greet ----
Hello World
-----end fn: greet

Here we see the output as above because, greet function is decorated by @trace and on top of it @twice

As a result, greet gets wrapped by trace which causes every execution of the greet having the trace logs.

And on top of trace is twice, which wraps these entire function to execute twice.

Now let us SWAP the order of the decorators

Output:begin executing fn: wrapper ----
Hello World
Hello World
-----end fn: wrapper

Upon swap of decorator order, the other most decorator becomes @trace, hence @twice causes the greet function to execute twice which is encapsulated with debug logs provided my @trace

In most practical purposes there is no limit on decorator nesting, until you are able to maintain code sanity!

Now that we are getting comfortable with decorators, we can think of different use cases of decorators. So can there be a decorator which returns a wrapper function, which in turn returns a wrapper? Or can we pass parameters to a decorator?

In the upcoming Python decorators [Part 3] article, we will talk about Higher Order Decorators.

If you are still shaky with the concept of decorators, it is highly recommended to go through Python decorators [Part 1]

--

--

Sumeet Sarkar

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