2. Iterators, Generators & Functional Tools
First-Class Functions, Closures & Decorators
Learn how functions work as objects in Python, how closures remember enclosing state, and how to write clean decorators with @functools.wraps and optional parameters.
- Pass and return functions as first-class objects and build lexical closures
- Write reusable decorators using @functools.wraps to preserve metadata
- Create parameterized decorators using a three-layer factory function
In frameworks like Flask, FastAPI, Pytest, and Dataclasses, you see @ symbols everywhere: @app.get("/users"), @pytest.fixture, @dataclass. Those are decorators—one of Python's cleanest features for adding cross-cutting behavior (timing, logging, caching, authentication) without cluttering your core business logic.
Why It Matters: Before vs After
Without decorators, adding timing or access logging to 10 functions means duplicating the same start = time.perf_counter() boilerplate inside every single function—making bugs harder to spot and logic harder to test:
# Before: timing boilerplate mixed directly into business logic
def compute_tax(amount: float) -> float:
start = time.perf_counter()
result = round(amount * 1.08, 2)
print(f"compute_tax took {(time.perf_counter() - start) * 1000:.2f} ms")
return result
# After: business logic stays 1 line; timing lives in a reusable decorator
@timer
def compute_tax(amount: float) -> float:
return round(amount * 1.08, 2)To understand decorators effortlessly, you only need two building blocks: first-class functions and closures.
Calling greet() enters wrapper(), runs before-logic, calls the original func via @functools.wraps, then runs after-logic.
1. Functions Are Objects & How Closures Capture Variables
In Python, a function is an object just like a string or integer. You can assign it to a variable, pass it as an argument, or return a newly created inner function from an outer function:
def make_multiplier(factor: int):
def multiply(number: int) -> int:
return number * factor # Captures `factor` from enclosing scope!
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15Deep Mental Model: How a Closure Remembers State
Normally, when make_multiplier(2) returns, its local variables would vanish. However, Python detects that the inner multiply function references factor from the enclosing scope, so Python packs factor = 2 into a hidden cell object attached to multiply.__closure__:
doubleholds its own cell (factor = 2).tripleholds a completely separate cell (factor = 3).- If you only read
factor, it works automatically. If you want to reassign an outer variable (likecount += 1), you must declarenonlocal countinside the inner function—otherwise Python treatscountas a brand-new local variable and raisesUnboundLocalError!
2. How a Decorator Works Step by Step
A decorator is simply a callable that receives func, defines wrapper(*args, **kwargs) (a closure capturing func), and returns wrapper:
import functools
import time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed_ms = (time.perf_counter() - start) * 1000
print(f"[timer] {func.__name__} took {elapsed_ms:.2f} ms")
return result
return wrapper
@timer
def sum_range(n: int) -> int:
"""Return sum from 0 to n - 1."""
return sum(range(n))
print(sum_range(100_000))Writing @timer above def sum_range runs at function definition time (import time) and is exact syntactic sugar for:
sum_range = timer(sum_range)Notice two distinct moments in time:
- Definition time:
timer(sum_range)runs once and rebinds the namesum_rangetowrapper. - Call time: Calling
sum_range(100_000)actually callswrapper(100_000), which runs your before-hook, forwards*args, **kwargsto the originalfunc, runs your after-hook, and returnsresult.
Two classic bugs break decorators:
- Forgetting
@functools.wraps(func)turnssum_range.__name__into"wrapper"and erases its docstring. - Forgetting
return resultinsidewrappermakes every decorated function silently returnNone!
3. Decorators That Accept Arguments (3-Layer Factory)
What if you want @repeat(times=3)? Because @repeat(times=3) is evaluated as a function call before wrapping func, you add one outer factory layer:
import functools
def repeat(times: int):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
last_result = None
for _ in range(times):
last_result = func(*args, **kwargs)
return last_result
return wrapper
return decorator
@repeat(times=3)
def greet(name: str):
print(f"Hello, {name}!")
greet("Maya")Trace the three layers from outside in:
repeat(times=3)runs first, storestimes = 3in a closure, and returnsdecorator.- Python applies
@decoratortogreet, runningdecorator(greet)and returningwrapper. - Every call to
greet("Maya")executeswrapper("Maya").
Decision Table: Plain vs Parameterized Decorators
| Pattern | Signature | Use When |
|---|---|---|
Plain decorator @timer | def timer(func): | Zero configuration needed |
Parameterized @repeat(times=3) | def repeat(times): def decorator(func): | Caller passes settings or thresholds |
Stacked @auth + @timer | Bottom-up wrapping (auth(timer(fn))) | Combining orthogonal concerns; note outer runs first at call time |
Try It Yourself in the Playground
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Write a closure make_counter(start=0) that returns a next_id() function. Each call to next_id() should increment count using nonlocal and return the new integer.
Quick Checkpoints
What does @my_decorator placed directly above def process(): actually do?
Why should every wrapper function inside a decorator be decorated with @functools.wraps(func)?