Back
+15 XP
Concept

The Decorator Pattern: Wrapping Callables

A decorator takes a function, wraps extra behavior around it, and returns the wrapper. The `@` syntax is syntactic sugar for `func = decorator(func)` 🎀.

python
def announce(func):
    def wrapper():
        print("Starting task... ⚡")
        func()
        print("Task finished! 🏁")
    return wrapper

@announce
def work():
    print("Crunching payload numbers 💻")

work()

# 34. The Decorator Pattern: Wrapping Callables A decorator takes a function, wraps extra behavior around it, and returns the wrapper. The `@` syntax is syntactic sugar for `func = decorator(func)` 🎀. ```python def announce(func): def wrapper(): print("Starting task... ⚡") func() print("Task finished! 🏁") return wrapper @announce def work(): print("Crunching payload numbers 💻") work() ``` Decorators allow logging, authentication, and telemetry without touching your original business logic. The wrapper transparently intercepts the invocation! 🎀 --- ### Question What does `@my_decorator` placed directly above `def process():` translate to? 🧠 - [ ] a. `process = my_decorator(process)` 🎀 - [ ] b. `import my_decorator as process` - [ ] c. `process = my_decorator()` - [ ] d. `sys.settrace(my_decorator)` --- ### Challenge Write a decorator `bracket_logger(func)` that prints `[BEGIN]`, executes `func()`, and prints `[END]`. Decorate `def ping(): print('pong')`. Call `ping()`. 🎯 <details> <summary>Solution</summary> ```python def bracket_logger(func): def wrapper(): print("[BEGIN]") func() print("[END]") return wrapper @bracket_logger def ping(): print("pong") ping() ``` </details>

Checkpoint

What does `@my_decorator` placed directly above `def process():` translate to? 🧠

Practice

Write a decorator `bracket_logger(func)` that prints `[BEGIN]`, executes `func()`, and prints `[END]`. Decorate `def ping(): print('pong')`. Call `ping()`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks