Python · Module 08: Intermediate & Modern PythonTutorial 23 of 30

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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!

Visual: How `@timer` Wraps Your Function Like Gift Paper Without Editing Its Code
@timer Wrapper (1. Start stopwatch BEFORE calling func)2. Your Original Function: fetch_users()Runs untouched — doesn't even know it's being timed!@timer Wrapper (3. Stop stopwatch AFTER & return original result)
PYTHON
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 @timer above def slow_sum(n): is 100% identical to writing slow_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:

PYTHON
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

Tracing a @log_call Decorator Execution
Interactive Line-by-Line Execution Trace · Step 1 of 4
1def log_call(fn):
2 def wrapper(x):
3 print(f"Calling {fn.__name__}({x})")
4 return fn(x)
5 return wrapper
6→@log_call
7def double(n): return n * 2
8ans = double(5)
9print("Result:", ans)
Variables in Memory
double<wrapper around double>func
Console Output
(nothing printed yet)
What just happened: @log_call immediately wraps double -> double now points to wrapper!

Quick Quiz: Module 8.2 — Decorators & Context Managers

Q1.What is `@my_dec` placed above `def foo():` shorthand for?
Q2.Why should you put `@functools.wraps(func)` on your decorator's inner `wrapper`?
Q3.In a `@contextmanager` generator, where does the user's `with` block code execute?

Keep Exploring: Related Lessons & Tools

All Courses →