Course Content
Intermediate Python: Arguments, Scopes and Decorators
Intermediate Python: Arguments, Scopes and Decorators
Chaining Decorators
Chaining decorators in Python is a powerful feature that allows you to apply multiple decorators to a single function. Each decorator modifies or enhances the function in some way, and they are applied in a specific order. Here's a practical example to illustrate chaining decorators:
Two Simple Decorators
First, let's define two simple decorators:
Chaining Decorators
Now, let's apply these decorators to a single function:
def decorator_one(func): def wrapper(): print('Decorator one start') func() print('Decorator one end') return wrapper def decorator_two(func): def wrapper(): print('Decorator two start') func() print('Decorator two end') return wrapper @decorator_one @decorator_two def greet(): print("Hello!") greet()
In each decorator, there is code that runs before moving on to the next decorator and after the completion of this decorator. It works in a layered manner. They are applied in the order they are listed, from top to bottom. The output of the upper decorator becomes the input for the next one down. This layering can add multiple functionalities to the original function.
Execution Order
When greet()
is called, the execution order will be:
- From
decorator_one
the first print is executed; - Inside
decorator_one
, fromdecorator_two
the first print is executed; - Finally, the original
greet
function is executed; - Then, move backward and finish executing the
decorator_two
by printing the message; - The whole code is finished by executing the last print statement in the
decorator_one
.
The output will be:
Chaining decorators is a powerful way to extend the behavior of functions in a modular and readable way.
Hope the next challenge helps you to better understand this topic.
Thanks for your feedback!