Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Chaining Decorators | Decorators
Intermediate Python Techniques
course content

Contenido del Curso

Intermediate Python Techniques

Intermediate Python Techniques

1. Packing and Unpacking
2. Arguments in Function
3. Function as an Argument
4. Variable Scope
5. Decorators

bookChaining 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:

1234567891011121314151617181920
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()
copy

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:

  1. From decorator_one the first print is executed;
  2. Inside decorator_one, fromdecorator_two the first print is executed;
  3. Finally, the original greet function is executed;
  4. Then, move backward and finish executing the decorator_two by printing the message;
  5. 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.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 5. Capítulo 5
We're sorry to hear that something went wrong. What happened?
some-alt