Skip to content
Tech Interview Prep
Technical interview guide

Decorators & Context Managers

Wrapping a function's behavior without changing its code, and guaranteeing setup/teardown runs even when something fails.

Minutes to read
4
Practice MCQs
25
Interview Q&A
25
Edition
v3
Editorial status
Reviewed

Scope: Python 3.14 decorator, context manager, contextlib, and asynchronous context manager semantics.

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: @d above def f is f = 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 the as value. __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__, which inspect.signature follows.
  • 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.

caller authorize wrapper cache wrapper original f

When to use and when not to

SituationDecoratorContext manager
Behavior applies to every call of a functionYesNo
Resource should be released at a visible block endHolds it for the whole functionYes
Need the function's signature to stay intact for DIOnly with functools.wrapsNot applicable
Optional or caller-owned resourceAwkwardUse nullcontext at the boundary
Async cleanupasync def wrapper with awaitasync with or AsyncExitStack
Variable number of resourcesNot applicableExitStack

Traps interviewers probe

  1. 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.
  2. Wrapper drops keywords. Forwarding only *args breaks keyword-only parameters with a missing-argument TypeError. Fix: forward *args, **kwargs exactly once.
  3. Missing metadata. A wrapper without @functools.wraps(fn) reports (*args, **kwargs) to inspect.signature, so DI containers inject nothing. Fix: apply @functools.wraps(fn) to every wrapper.
  4. Sync wrapper around a coroutine. A plain def that returns a coroutine logs near-zero duration and never sees its exception. Fix: write an async def wrapper that awaits the original, or provide a separate async variant.
  5. Retry catches BaseException. This intercepts SystemExit and 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 bare raise.

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 @authorize over @cache do, and what changes if you swap them?
  • Why does a stateful decorator object race under threads? self.calls += 1 is 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 the as value?
  • Why does @transactional around 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 aclosing release a suspended async generator's cursor deterministically, where a plain break leaves cleanup to finalization?

30-second outline.

  1. Definition: a decorator rebinds a name at definition time; a with suite brackets a block with paired entry and exit.
  2. Mechanism: stacked decorators apply bottom-up; __exit__ gets exception info and suppresses only on a truthy return.
  3. Trade-off: decorators hide per-call work; with exposes scope and ownership.
  4. Trap: name one concrete failure, such as a dropped keyword, a missing wraps, or a commit in finally, and its fix.
  5. 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.