Chaining and Stacking Decorators
Swipe to show menu
When working with decorators in Python, you often need to apply more than one decorator to a single function. This is known as stacking or chaining decorators. The way you stack decorators is by placing multiple decorator lines, one after another, directly above the function definition. The order in which you stack decorators matters because it affects how the function is wrapped and how each decorator interacts with the others. The decorator closest to the function is applied first, and each subsequent decorator wraps the result of the previous one. This means that the decorator at the top of the stack is the outermost wrapper, while the one closest to the function is the innermost.
The example below defines two decorators, decorator_one and decorator_two, stacked above a function called greet. The stacking order determines how the decorators are applied.
123456789101112131415161718192021222324252627# Prints messages before and after the function call def decorator_one(func): def wrapper(*args, **kwargs): print("Decorator One: Before") result = func(*args, **kwargs) print("Decorator One: After") return result return wrapper # Also prints messages before and after the function call def decorator_two(func): def wrapper(*args, **kwargs): print("Decorator Two: Before") result = func(*args, **kwargs) print("Decorator Two: After") return result return wrapper # Stacking decorators # decorator_two is applied first (innermost), # then decorator_one wraps the result (outermost) @decorator_one @decorator_two def greet(name): print(f"Hello, {name}!") greet("Alice")
Notice that decorator_two is applied first to greet, and then decorator_one wraps the result. This means the decorator closest to the function is the innermost, and the topmost is the outermost. The order of stacking is important, as it affects the behavior of your decorated function.
Thanks for your feedback!
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat