Overview
Curated: · Written: · Reviewed:
Decorators & Context Managers
In one line
A decorator receives a function or class when its def executes and rebinds the name to whatever it returns, so it runs once at definition time and again on every call of the wrapper. A context manager brackets a with suite so entry and exit code always pair. Reach for a decorator for cross-cutting call behavior such as auth, caching, retry or timing, and for with when a resource's lifetime should be visible at the call site.
Key definitions
- Decoration:
@dabovedef fisf = d(f), evaluated once when the definition executes. - Wrapper: the closure a decorator returns. It keeps the original callable and configuration in closure cells.
- Descriptor binding: how a function stored on a class receives
self. Plain functions implement__get__, so a wrapper that is a plain function binds correctly. A bare callable instance does not. - Context manager protocol:
__enter__produces theasvalue.__exit__(type, value, tb)runs once entry succeeds, receives three Nones on normal completion, and suppresses only when it returns a truthy value. functools.wraps: copies__name__,__doc__and annotations, and sets__wrapped__, whichinspect.signaturefollows.ExitStack: a LIFO stack of exit callbacks, built dynamically.pop_all()transfers ownership of the cleanups.
How it works
Decorator expressions and application run at definition time. The wrapper runs at call time. Stacked decorators apply bottom-up: @authorize above @cache means authorize(cache(f)), so cache wraps the raw function and authorize checks before the cache is consulted.
For with, Python calls __enter__, binds its result, runs the body, then calls __exit__ with exception details or three Nones. If __enter__ itself raises, __exit__ is never called, so acquire-then-fail inside __enter__ needs its own rollback.
With @contextmanager, an exception from the body is thrown into the yield. If the generator catches it and returns, the exception is suppressed.
When to use and when not to
| Situation | Decorator | Context manager |
|---|---|---|
| Behavior applies to every call of a function | Yes | No |
| Resource should be released at a visible block end | Holds it for the whole function | Yes |
| Need the function's signature to stay intact for DI | Only with functools.wraps | Not applicable |
| Optional or caller-owned resource | Awkward | Use nullcontext at the boundary |
| Async cleanup | async def wrapper with await | async with or AsyncExitStack |
| Variable number of resources | Not applicable | ExitStack |
Traps interviewers probe
- Late binding in loops. A decorator factory that closes over a loop variable gives every wrapper the final value. Fix: build each decorator through a factory function, such as
make_tagger(name), so each call gets its own scope. - Wrapper drops keywords. Forwarding only
*argsbreaks keyword-only parameters with a missing-argument TypeError. Fix: forward*args, **kwargsexactly once. - Missing metadata. A wrapper without
@functools.wraps(fn)reports(*args, **kwargs)toinspect.signature, so DI containers inject nothing. Fix: apply@functools.wraps(fn)to every wrapper. - Sync wrapper around a coroutine. A plain
defthat returns a coroutine logs near-zero duration and never sees its exception. Fix: write anasync defwrapper that awaits the original, or provide a separate async variant. - Retry catches BaseException. This intercepts
SystemExitand cancellation, so a malformed-file exit gets retried with sleeps before it finally exits. Fix: catch only the transient exception types, bound the attempts, and use a bareraise.
Interview tips
Opening. Name the three phases first: decoration at definition time, wrapper execution at call time, and for with, entry, body and exit. Then state which phase the problem sits in.
Expected follow-ups.
- What does
@authorizeover@cachedo, and what changes if you swap them? - Why does a stateful decorator object race under threads?
self.calls += 1is several bytecodes, and a dict get-then-set needs the same lock. Wrapping only one of them leaves the other wrong. - Why does
__exit__never receive the manager or theasvalue? - Why does
@transactionalaround a function that calls an external HTTP service hold a pooled connection too long? Commit before any notification, and keep the transaction to the writes. - Why does
aclosingrelease a suspended async generator's cursor deterministically, where a plainbreakleaves cleanup to finalization?
30-second outline.
- Definition: a decorator rebinds a name at definition time; a
withsuite brackets a block with paired entry and exit. - Mechanism: stacked decorators apply bottom-up;
__exit__gets exception info and suppresses only on a truthy return. - Trade-off: decorators hide per-call work;
withexposes scope and ownership. - Trap: name one concrete failure, such as a dropped keyword, a missing
wraps, or a commit infinally, and its fix. - Close on the fix, then stop.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.