![]() |
VOOZH | about |
Decorator chaining is the process of applying multiple decorators to a single function. Each decorator wraps the function and adds its own functionality, allowing multiple behaviors to be combined without modifying the original code. Following sections explains how decorator chaining works, the order of execution and how multiple decorators interact with one another.
Example: Chaining Multiple Decorators
Decorator 1 - Before Function Decorator 2 - Before Function Hello, World! Decorator 2 - After Function Decorator 1 - After Function
A decorator is a function that can take a function as an argument and extend its functionality and return a modified function with extended functionality.
When multiple decorators are used, Python applies them from the bottom up. The decorator closest to the function is applied first, and the resulting function is then passed to the decorator above it. This order determines how the decorators interact and affect the final behavior of the function.
Example:
is equivalent to:
Here, decor2 wraps the original num() function first, and the function returned by decor2 is then wrapped by decor1.
Explanation:
@decor1
@decor2
def num():
pass
Example 1: Two decorators are applied to num() to demonstrate decorator chaining. Python applies decorators from the bottom up, so @decor executes first and its result is then passed to @decor1 for further processing.
400
Explanation:
Example 2: Multiple decorators are applied to sayhellogfg() to show how decorator chaining works. Each decorator contributes its own behavior, resulting in a combined effect when the function is executed.
************ @@@@@@@@@@@@ Hello @@@@@@@@@@@@ ************ GeekforGeeks
Explanation:
Decorators can also accept arguments, allowing their behavior to be customized when applied to a function. These decorators return another decorator function, which then wraps the target function. Multiple parameterized decorators can be chained in the same way as regular decorators.
Example:
Welcome Hello Hello
Explanation: