Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Chaining and Stacking Decorators | Mastering Python Decorators
Functional Programming Concepts in Python

Chaining and Stacking Decorators

Sveip for å vise menyen

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")
Note
Note

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.

question mark

In what order are stacked decorators applied in Python?

Velg alle riktige svar

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 4. Kapittel 5

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 4. Kapittel 5
some-alt