A Python Decorator Replaces a Function with Whatever It Returns
@decorator above def f is shorthand for f = decorator(f). Whatever the decorator returns takes the function's name: usually a wrapper that runs code before and after the original, sometimes the original itself after registering it somewhere. Forgetting the return, or the wrapper's arguments, breaks the decorated function in ways that look unrelated to the decorator.
A Wrapper Around the Call
import functools
def fence(func):
@functools.wraps(func) # keep func's name and docstring
def wrapper(*args, **kwargs): # accept any signature
print("+" * 10)
result = func(*args, **kwargs)
print("+" * 10)
return result # pass the result through
return wrapper # this replaces func
@fence
def log_message(text: str) -> None:
print(text)
Decorators That Take Arguments
@fence(symbol="#") first calls fence(symbol="#"), which must return the actual decorator, hence three levels:
def fence(symbol: str = "+"):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(symbol * 10)
return func(*args, **kwargs)
return wrapper
return decorator
Registration Decorators: How Web Routes Work
A decorator doesn't have to wrap anything. FastAPI's @app.get("/items") (or @router.get on an APIRouter, later added with app.include_router()) records the function in the app's routing table with its path and method, then returns it unchanged. That's how a plain function becomes the handler for a URL.
References
- Programming Languages MOC - hub for Python notes.
- FastAPI MOC - hub for FastAPI notes.
- Python Ignores Type Hints at Runtime, So Only a Checker or a Library Enforces Them - typing decorators with
Callable. - Python documentation: functools.wraps - preserving the wrapped function's metadata.
- Python glossary: decorator - the
@syntax as function application.
Review cards
Flashcard Why wrap the inner function with `functools.wraps`?
Otherwise the decorated function's __name__ and docstring become the wrapper's, which confuses logs, debuggers and frameworks that read signatures.
Flashcard What breaks when a decorator's wrapper doesn't take `*args, **kwargs`?
The wrapper accepts only the parameters it declares, so decorating a function with other parameters makes its calls fail with TypeError. *args, **kwargs passes any arguments through to func.
Quiz Where do `*args, **kwargs` go so a decorator works with any function?
- On the inner
wrapper, which passes them on:func(*args, **kwargs) - On the decorated function:
def func(*args, **kwargs) - On the decorator itself:
def fence(*args, **kwargs) - Nowhere: the
@syntax forwards arguments automatically
The decorator receives only func; the wrapper is what callers actually call, so it must accept any arguments and forward them.