Decorators That Accept Arguments
To pass arguments to a decorator (like `@repeat(3)`), wrap it in an outer factory function. It returns the actual decorator that wraps the target callable 🧅.
import functools
def repeat(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(times=3)
def cheer():
print("Ship it! 🚀")
cheer()
# 36. Decorators That Accept Arguments To pass arguments to a decorator (like `@repeat(3)`), wrap it in an outer factory function. It returns the actual decorator that wraps the target callable 🧅. ```python import functools def repeat(times): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): result = None for _ in range(times): result = func(*args, **kwargs) return result return wrapper return decorator @repeat(times=3) def cheer(): print("Ship it! 🚀") cheer() ``` Remember the three layers: The outer function takes config options, the middle decorator takes `func`, and the innermost wrapper handles each live call. 🧅 --- ### Question Why does a configurable decorator require three nested function layers? 🧠- [ ] a. Outer accepts configuration, middle accepts the function, inner executes the call 🧅 - [ ] b. Because Python's recursion limit mandates three scopes - [ ] c. To bypass OS process permissions - [ ] d. It is a strict requirement imposed by the CPython garbage collector --- ### Challenge Write a decorator factory `prefix_output(tag)` that prepends `f'[{tag}] '` to the string returned by the decorated function. Decorate `def status(): return 'ONLINE'`. Print `status()`. 🎯 <details> <summary>Solution</summary> ```python import functools def prefix_output(tag): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): return f"[{tag}] {func(*args, **kwargs)}" return wrapper return decorator @prefix_output("STATUS") def status(): return "ONLINE" print(status()) ``` </details>