Member-only story
Decorators are versatile tools for enhancing your Python functions. But did you know they could also be nested to further improve organization and flexibility? Nested decorators enable you to dynamically apply several layers of functionality to your target functions — all within a single line of syntactic sugar. Let’s dive into creating and understanding nested decorators.
What Are Nested Decorators?
Simply put, a nested decorator is a decorator applied to another decorator. To understand their structure better, consider two separate decorators, decorator1
and decorator2
. Applying both decorators on a function my_function
would look like this:
@decorator2
@decorator1
def my_function():
...
This shorthand notation translates to:
def my_function():
...
my_function = decorator2(decorator1(my_function))
When combining nested decorators, each subsequent decorator receives the previous one’s output as input, forming a chain.