Decorators: Functions That Wrap Functions
@app.get(...) in FastAPI and every @pytest.fixture is a decorator. A decorator takes a function, wraps extra behavior around it, and gives you back a function you call exactly as before. You already know the two ingredients, functions as values and closures. This lesson puts them together.After this lesson, you will be able to:
- Write a decorator that wraps a function with extra behavior
- Explain that @decorator above a def is the same as func = decorator(func)
- Write decorators for timing, logging, and caching
- Stack decorators and predict the order they apply and run
- Write a decorator that takes its own arguments
- Use functools.wraps so a wrapped function keeps its name and docstring
Before you start
#Decorators
@decorator syntax is just shorthand.#How Decorators Work Under the Hood
# Step 1: A decorator is just a function that takes a function
def shout(func):
"""A decorator that converts the result to uppercase."""
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
# Step 2: Apply it manually (the old way)
def greet(name):
return f"Hello, {name}!"
greet = shout(greet) # wrap greet with shout
print(greet("Alice")) # HELLO, ALICE!
# Step 3: Apply it with @ syntax (the modern way -- identical result)
@shout
def greet_v2(name):
return f"Hello, {name}!"
print(greet_v2("Bob")) # HELLO, BOB!@shout above greet_v2 is exactly equivalent to writing greet_v2 = shout(greet_v2). The @ syntax is just cleaner.You define a decorator without @functools.wraps. What does the decorated function's __name__ return?
#Practical Decorator: Timing
import time
def timer(func):
"""Measure how long a function takes to run."""
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.4f} seconds")
return result
return wrapper
@timer
def slow_sum(n):
"""Sum numbers from 0 to n using a loop."""
total = 0
for i in range(n):
total += i
return total
@timer
def fast_sum(n):
"""Sum numbers from 0 to n using the formula."""
return n * (n - 1) // 2
slow_sum(1_000_000) # slow_sum took 0.0523 seconds
fast_sum(1_000_000) # fast_sum took 0.0000 seconds#Practical Decorator: Logging
def log_call(func):
"""Log every call to a function with its arguments."""
def wrapper(*args, **kwargs):
args_str = ", ".join([repr(a) for a in args])
kwargs_str = ", ".join([f"{k}={v!r}" for k, v in kwargs.items()])
all_args = ", ".join(filter(None, [args_str, kwargs_str]))
print(f"CALL: {func.__name__}({all_args})")
result = func(*args, **kwargs)
print(f" -> returned {result!r}")
return result
return wrapper
@log_call
def add(a, b):
return a + b
@log_call
def multiply(a, b):
return a * b
add(3, 5)
# CALL: add(3, 5)
# -> returned 8
multiply(4, 7)
# CALL: multiply(4, 7)
# -> returned 28#Practical Decorator: Simple Cache (Memoization)
def cache(func):
"""Cache results to avoid recomputing for the same inputs."""
memo = {}
def wrapper(*args):
if args in memo:
print(f" (cache hit for {args})")
return memo[args]
result = func(*args)
memo[args] = result
return result
return wrapper
@cache
def fibonacci(n):
"""Compute the nth Fibonacci number recursively."""
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(10)) # 8 "cache hit" lines print first (the recursion reuses n = 1 to 8), then 55
print(fibonacci(10)) # one "cache hit" line, then 55fibonacci(30) would make over a million recursive calls. With the cache, it makes exactly 31 calls.functools.lru_cache is this same memoization, written once and tested. @property turns a method into something you read like an attribute, and you will meet it when you learn classes. Decorators can wrap classes too: @dataclass is a decorator that takes a class and returns a better one.#Stacking Decorators: Why Order Matters
@decorators and the order of application becomes its own puzzle: decorators are applied bottom-up at definition time, but control flows top-down through them at call time. The viz below makes both phases visible — toggle the modes and watch a cache HIT short-circuit before it ever reaches the inner function.#Decorator Factories: Decorators with Arguments
from functools import wraps
# Pattern: outer function takes arguments, returns the real decorator
def repeat(times: int = 2):
"""Decorator factory: call the wrapped function `times` times."""
def decorator(func): # the real decorator — takes the function
@wraps(func) # always use @wraps to preserve metadata
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result # the result of the last call
return wrapper
return decorator # return the decorator, not the wrapped function
# Usage: @repeat(times=3) calls repeat(3), which returns decorator
@repeat(times=3)
def say(word):
print(word)
return word.upper()
print(say("hi"))
# hi
# hi
# hi
# HI
# With no arguments, still write the parentheses: @repeat() uses the default of 2,
# while a bare @repeat would pass the function in as `times`
@repeat()
def ping():
print("ping")
ping()
# ping
# pingrepeat(args) → decorator(func) → wrapper(*args, **kwargs). The factory layer holds configuration, the decorator layer captures the function, the wrapper layer executes the logic.@repeat(times=3) — the three-layer call hierarchy
Step through the recursive calls and returns to watch the call tree grow, results fill in, and the call stack change.
A recursion call tree for the supplied function, shown above its source code with a call stack panel beside it. It starts at step 0 with an empty tree and empty stack; each step adds a call or fills in a return value, until the tree is complete.
def repeat(times): # FACTORY
def decorator(func): # DECORATOR
def wrapper(*args, **kw): # WRAPPER
...
return wrapper
return decorator
@repeat(times=3) # rewritten as: say = repeat(3)(say)
def say(word):
...
say("hi") # finally invokes wrapper("hi")repeat(3) returns decorator), then the decorator runs (decorator(say) returns wrapper), and finally say is rebound to wrapper. Only later, at call time, does wrapper("hi") actually execute. Each (arg) you see in @repeat(3) is a real function call, not part of the @ syntax.Which of these does @functools.wraps(func) NOT copy from the original function to the wrapper?
#Putting It All Together
Here is a decorator that combines timing, logging, and caching:
import time
from functools import wraps
def smart_cache(func):
"""A decorator that caches results and logs timing."""
memo = {}
@wraps(func) # preserves the original function's name and docstring
def wrapper(*args):
if args in memo:
print(f" {func.__name__}{args}: cache hit")
return memo[args]
start = time.time()
result = func(*args)
elapsed = time.time() - start
memo[args] = result
print(f" {func.__name__}{args}: computed in {elapsed:.6f}s")
return result
return wrapper
@smart_cache
def expensive_calculation(n):
"""Simulate an expensive computation."""
total = 0
for i in range(n * 1000):
total += i ** 0.5
return total
print(expensive_calculation(100)) # computed in 0.012345s
print(expensive_calculation(100)) # cache hit (instant)
print(expensive_calculation(200)) # computed in 0.024567s#Code Playground
Tests: Build decorators, stack them, and check what the wrapped function still reports about itself!
#Key Takeaways
- A decorator wraps a function with extra behavior. Write
@decoratorabove a function definition. The original function is unchanged; the wrapper adds timing, logging, caching, or any other cross-cutting concern. @decoratorabovedef fis exactlyf = decorator(f). It runs once, when the function is defined.- Stacked decorators apply bottom-up and run top-down.
- A decorator that takes arguments is a factory with three layers: the factory holds the settings, the decorator captures the function, and the wrapper does the work.
- Always put
@wraps(func)on the wrapper, so the decorated function keeps its__name__and__doc__.
What does a decorator do?