Decorators and context managers
Two features that make Python code elegant: decorators wrap functions with extra behaviour (timing, logging, caching, permission checks), and context managers guarantee that setup and cleanup always happen together (with open(...)). Frameworks like Flask, FastAPI and pytest use both everywhere.
Functions are objects
A decorator relies on two facts: functions can be passed around like any value, and you can define a function inside another function:
Your first decorator
A decorator is a function that takes a function and returns a new, improved one:
*args, **kwargs lets the wrapper accept any arguments and pass them through unchanged.
Useful real decorators
Timing
Always use @wraps(func), or every decorated function will be called "wrapper" in tracebacks and tools.
Caching
The standard library ships a caching decorator. Watch it turn an exponentially slow function into an instant one:
@lru_cache(maxsize=1000) is the variant with a size limit.
Decorators with arguments
Add one more layer of function to accept arguments:
Decorators in frameworks
You'll recognise this shape everywhere:
@app.get("/users/{user_id}") # FastAPI: register a route
async def get_user(user_id: int): ...
@pytest.fixture # pytest: provide test data
def db(): ...
@login_required # Django: permission check
def dashboard(request): ...Context managers
A context manager runs setup code when a with block starts and cleanup code when it ends, even if an error happens:
Writing one with contextlib
A class-based context manager
__exit__ receives the exception (if any). Returning True swallows it; returning None/False lets it continue.
Handy built-in context managers
Practice
- Write a
@log_callsdecorator that prints the function name and arguments every time it's called. - Write a
@validate_positivedecorator that raisesValueErrorif any numeric argument is negative. - Write a context manager
cd(path)that changes into a folder (os.chdir) and always changes back afterwards. Test it withos.getcwd().
1.What does @timed above a function definition mean?
2.Why use functools.wraps in a decorator?
3.When does the cleanup code in a context manager run?