Function Decorators & Syntactic Sugar (@decorator)
1Concept
A decorator is a callable that takes a function as an argument and returns an augmented wrapper function. The `@decorator` syntax is syntactic sugar for `func = decorator(func)`.
2Architecture Diagram
@timer
def fetch_data(): ...
|
v Equivalent to:
fetch_data = timer(fetch_data)3Code Example
Python 3.12
import time
def timing_decorator(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
duration = time.perf_counter() - start
print(f"[{func.__name__}] Executed in {duration:.6f}s")
return result
return wrapper
@timing_decorator
def compute_heavy_task(n: int) -> int:
return sum(i * i for i in range(n))
res = compute_heavy_task(100_000)
print(f"Result: {res}")4Expected Output
[compute_heavy_task] Executed in 0.005821s Result: 333328333350000
5Key Takeaways
- ✓Decorators execute at function DEFINITION time (import time), not call time.
- ✓Always return the inner wrapper from the outer decorator function.
- ✓Decorators allow cross-cutting concerns (logging, auth, caching) without modifying core logic.