Core Python·Lesson 18 of 67·intermediate
Decorators and context managers
Wrap a function without touching it, build decorators that take arguments, and write your own with-blocks so setup and cleanup always pair up.
In this lesson · 20 min
- →Explain closures, and how a decorator is built from one
- →Write decorators that preserve the wrapped function's identity
- →Build decorators that take arguments
- →Cache expensive calls with functools.cache
- →Write context managers as classes and with @contextmanager
Decorators and context managers solve the same problem from two directions: code that has to run around something else. Retries, timing, caching and logging around a function; setup and cleanup around a block.
Closures
A function defined inside another function remembers the variables it was created with, even after the outer call has returned:
That is all a decorator is: a function that takes a function and returns a replacement.
A first decorator
@announced above a def means exactly that reassignment:
*args, **kwargs in the wrapper is what makes a decorator work on any function, whatever its
signature.
Keep the function’s identity
Replacing a function loses its name and docstring, which breaks documentation tools, tracebacks
and anything that inspects the signature. functools.wraps copies them across:
Decorators that take arguments
A decorator with arguments is a function that returns a decorator — one more layer:
Read it outside-in: retry(attempts=4) runs first and returns decorator, which is then applied
to flaky_call.
Stacking
Decorators apply bottom-up — the one nearest the def wraps first:
Caching
functools.cache remembers what a function returned for a given set of arguments. For anything
pure and expensive — an embedding, a tokenisation, a parsed config — it is a one-line win:
functools.lru_cache(maxsize=1024) is the bounded version — use it when the set of inputs is
unbounded, so the cache cannot grow forever.
Context managers
A with block guarantees that cleanup runs, whatever happens inside. Implementing __enter__
and __exit__ makes your own object work that way:
__exit__ receives the exception if one was raised. Returning False lets it propagate;
returning True suppresses it — which you almost never want.
@contextmanager
For most cases, a generator is less ceremony. Everything before yield is setup, everything
after is cleanup, and try/finally is what makes the cleanup unconditional:
contextlib has ready-made ones worth knowing:
Try it yourself
Write the decorator logged(function): it appends call NAME to CALLS before running, returns the result unchanged, and preserves the wrapped function's name and docstring.
Write the context manager stage(name) with @contextmanager. It appends start NAME on entry and end NAME on exit — even when the block raises — and yields the name.
Check yourself
What does @functools.wraps(function) do to the wrapper?
Check yourself
In a @contextmanager generator, why must the yield be inside a try/finally?
Recap
- A closure is an inner function that remembers the names it was created with; a decorator is a function that takes a function and returns its replacement.
@decoratorabove adefis justf = decorator(f).- Accept
*args, **kwargsin the wrapper, and always apply@functools.wraps. - A decorator with arguments is one extra layer: a function returning a decorator.
- Stacked decorators apply bottom-up.
functools.cachememoises a pure function with hashable arguments;lru_cache(maxsize=...)bounds it.withneeds__enter__/__exit__, or a@contextmanagergenerator whoseyieldsits inside atry/finally.