8.2 Decorators (@timer, @wraps) & Custom Context Managers
Demystify Python's @decorator syntax once and for all! Build reusable @timer and @retry wrappers without editing function bodies, and write custom `with` context managers.
1. What Is a Decorator? (The Gift-Wrapping Analogy)
In Python, functions are first-class objects — you can pass a function into another function and return a new function back.
A Decorator is simply a wrapper function that takes your original function, gift-wraps extra behavior before and after it (logging, timing, auth checks, caching), and hands back the wrapped version — without modifying a single line of your original function!
import time
from functools import wraps
def timer(func):
@wraps(func) # Preserves func.__name__ and docstring!
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs) # Call original function
elapsed = (time.perf_counter() - start) * 1000
print(f"{func.__name__} took {elapsed:.2f} ms")
return result # Don't forget to return result!
return wrapper
@timer
def slow_sum(n):
return sum(range(n))
print(slow_sum(100_000))
Note: Writing
@timerabovedef slow_sum(n):is 100% identical to writingslow_sum = timer(slow_sum).
2. Custom Context Managers (@contextmanager)
Remember how with open(...) automatically cleans up files? You can create your own with blocks (for database transactions, temporary directories, or timing code blocks) in 6 lines using contextlib.contextmanager:
from contextlib import contextmanager
import time
@contextmanager
def measure_block(label):
start = time.perf_counter()
try:
yield # Everything inside the `with` block runs right here!
finally:
ms = (time.perf_counter() - start) * 1000
print(f"[{label}] finished in {ms:.2f} ms")
with measure_block("Data Prep"):
nums = [i * i for i in range(50_000)]
3. Interactive Trace: Calling a Decorated Function
Quick Quiz: Module 8.2 — Decorators & Context Managers
Keep Exploring: Related Lessons & Tools
All Courses →Convert Unix epoch seconds/milliseconds to ISO-8601 and local timezones, and bulk-generate UUID v4, time-ordered UUID v7, and sortable ULIDs.
Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.