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.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain decorator evaluation, application, and call-time execution as separate phases.

Answer

Three phases, three different times. Evaluation: the decorator expression is evaluated when the def statement executes. At import for a module-level function, or when the enclosing function runs for a nested one. Application: the resulting callable is invoked once with the function object, and its return value is rebound to the original name. Call time: whatever is now bound to that name runs on every call.

Python
import functools

def traced(fn):
    print(f"apply {fn.__name__}")          # application phase
    @functools.wraps(fn)
    def wrapper(*a, **kw):
        print(f"call {fn.__name__}")        # call-time phase
        return fn(*a, **kw)
    return wrapper

print("A: before def")
@traced
def add(a, b):
    return a + b
print("B: after def")
add(1, 2)
add(3, 4)

Output:

A: before def
apply add
B: after def
call add
call add

apply add prints once, between A and B: that is application, and it happened before any call. The two call add lines are call time. @traced is exactly add = traced(add); the traced name is looked up at evaluation, traced(add) runs at application.

phasewhencountwhat executes
evaluationdef statement executesonce per executiondecorator expression, e.g. route("/x")
applicationsame statement, immediately afteroncetraced(add); result bound to add
call timeeach add(...)per callwrapper body; may or may not call fn

Stacked decorators: @a over @b over def f evaluates a then b top-down, but applies bottom-up. f = a(b(f)).

Failure modes worth naming:

  • Import-time side effects. A registry decorator @route("/x") writes to a module-level dict once, at import. Assume it runs per call and you will double-register on importlib.reload, or ship a half-populated registry when import fails partway. Detect by asserting registry size after import and after a reload.
  • State captured at application time is process-wide. A cache dict created inside the decorator body is one object for the process lifetime. functools.lru_cache(maxsize=None) on a function with unbounded distinct arguments grows without bound: a leak, not a cache. Watch cache_info().currsize and misses.
  • Missing functools.wraps. add.__name__ becomes "wrapper" and inspect.signature no longer reflects add. Frameworks that dispatch on name or signature break silently. wraps copies __module__, __name__, __qualname__, __doc__, __dict__ and sets __wrapped__.
  • Async splits call time again. Calling an async def function returns a coroutine without running the body; the body runs at await. So an async def wrapper logs at await, not at call: timing placed there measures await, not invocation.

Alternatives and cost: writing add = traced(add) by hand is the same thing without the syntax; a class-based decorator is worth it when you need per-instance state or __get__; contextlib.ContextDecorator lets one object serve as both decorator and context manager. The cost is one extra Python frame per call, which matters in hot inner loops: there, inline the logic or push it to a C-level mechanism instead.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Why does `functools.wraps` matter beyond cosmetic metadata?

Answer

Core answer (first 90 seconds)

functools.wraps does two things. It copies the wrapped function's metadata onto the wrapper, and it sets wrapper.__wrapped__ = wrapped, the hook that signature-following introspection uses to see through the wrapper. Neither is cosmetic: pickling, dependency-injection frameworks and test tooling all read those attributes.

The copy is functools.update_wrapper(wrapper, wrapped). It assigns WRAPPER_ASSIGNMENTS: __module__, __name__, __qualname__, __annotations__, __doc__, and __type_params__ since Python 3.12, then updates wrapper.__dict__ from wrapped.__dict__ via WRAPPER_UPDATES, then sets __wrapped__.

Mechanism, with a trace

Python
import functools, inspect

def traced(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs)
    return wrapper

@traced
def charge(account_id: str, cents: int) -> bool:
    """Debit an account."""
    return True

Traced against CPython 3.12:

expressionwith @wrapswithout
charge.__name__'charge''wrapper'
charge.__doc__'Debit an account.'None
charge.__wrapped__original chargeAttributeError
inspect.signature(charge)(account_id: str, cents: int) -> bool(*args, **kwargs)
inspect.getfullargspec(charge)(*args, **kwargs)(*args, **kwargs)

The last row is the trap. inspect.signature follows __wrapped__ by default (follow_wrapped=True), but getfullargspec passes follow_wrapper_chains=False and still reports the wrapper's real (*args, **kwargs).

Why it bites in production

  • FastAPI builds request models and the OpenAPI schema from inspect.signature(endpoint). A decorator without wraps makes every path and query parameter vanish from the schema and from validation.
  • pickle resolves a function by __module__ plus __qualname__. Without wraps, __qualname__ is 'traced.<locals>.wrapper', which is not a module attribute, so pickling the decorated function raises PicklingError. With wraps, the qualname resolves back to the module attribute, the wrapper itself, and it succeeds.
  • Log lines and tracebacks print __name__, so every message says wrapper instead of charge.
  • WRAPPER_UPDATES copies __dict__, so attributes stashed on the original survive decoration: pytest markers (func.pytestmark), a hand-rolled func.cache. Without it they are silently dropped.

Trade-offs and when not to use it

wraps is right when the wrapper is transparent: same parameters, same return. When the wrapper genuinely changes the call contract (it adds a keyword, drops an argument, reorders them) copying the original signature is a lie, and inspect.signature hands callers a signature the wrapper cannot honour. Set wrapper.__signature__ explicitly to the real one, or skip the copy. functools.lru_cache and functools.singledispatch both call update_wrapper internally; that is the pattern to imitate.

Detection: assert inspect.signature(decorated) == inspect.signature(original) in a test, and check decorated.__name__ in a smoke test.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Implement and explain the three layers of a parameterized decorator.

Answer

The 90-second answer. A parameterized decorator is three nested callables, not two. The outer factory takes configuration and runs once, when the module is imported. It returns the decorator, which takes the function and also runs once, at definition time. That returns the wrapper, which takes the call's arguments and runs on every invocation. @retry(limit=3) is sugar for flaky = retry(limit=3)(flaky): two calls, in that order, both before flaky is ever called. Assumption: Python 3.11+, sync targets first, async noted below.

Python
import functools, time

def retry(limit=3, delay=0.0, exceptions=(Exception,)):
    # Layer 1: factory. Runs once, at import.
    if limit < 1:
        raise ValueError(f"limit must be >= 1, got {limit}")
    def decorator(fn):
        # Layer 2: decorator. Runs once, at definition.
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            # Layer 3: wrapper. Runs on every call.
            for attempt in range(1, limit + 1):
                try:
                    return fn(*args, **kwargs)
                except exceptions:
                    if attempt == limit:
                        raise
                    time.sleep(delay)
        return wrapper
    return decorator
#LayerRunsReceivesReturns
1factory retryonce, at importconfig: limit, delay, exceptionsthe decorator
2decoratoronce, at definitionthe function fnthe wrapper
3wrapperevery callthe call's *args, **kwargsfn's result, or re-raises

Worked trace.

Python
calls = 0

@retry(limit=3, delay=0.0)
def flaky():
    global calls
    calls += 1
    if calls < 3:
        raise ConnectionError(f"attempt {calls}")
    return "ok"

print(flaky())   # ok
print(calls)     # 3

At import: retry(limit=3, delay=0.0) passes the limit < 1 check and returns decorator; decorator(flaky) returns wrapper with __wrapped__ = flaky; the name flaky is rebound to wrapper. Then flaky() runs wrapper(): attempt 1 calls the original body, calls becomes 1, ConnectionError("attempt 1") is caught, 1 != 3 so it sleeps 0.0; attempt 2, calls becomes 2, raises, sleeps; attempt 3, calls becomes 3, 3 < 3 is false, returns "ok". If the third attempt had raised, attempt == limit re-raises the original ConnectionError: the wrapper never wraps it in a new exception.

Failure modes, with detection.

  • Collapsing layers 1 and 2: def retry(fn, limit=3) then @retry(limit=3) raises TypeError: retry() missing 1 required positional argument: 'fn' at import. Loud, and the reason the factory exists.
  • Collapsing layers 2 and 3: the factory returns the wrapper directly, so wrapper(flaky) is called at definition with the function as a call argument. Definition succeeds silently; the first call fails with NameError: name 'fn' is not defined. Detect by smoke-calling the decorated function at import.
  • Async mismatch: a sync wrapper around a coroutine function returns a coroutine; the try never sees the exception because it is raised on await, so retries never fire. Branch on inspect.iscoroutinefunction(fn) and await fn(...) inside the loop.
  • Missing functools.wraps: flaky.__name__ becomes "wrapper", inspect.signature reports (*args, **kwargs), and tracing and pytest fixtures break. Assert flaky.__wrapped__ is original.
  • Retrying on bare Exception: a deterministic ValueError from bad input is retried limit times with delay between, tripling p99 for a call that can never succeed. Narrow the exceptions tuple and count retries per exception type in metrics.
  • Mutable state in the factory: a token bucket defined in layer 1 is shared by every call and every thread of that decorated function. Per-call state belongs in the wrapper.

Trade-offs. functools.lru_cache is the same three layers with maxsize as config. A class-based decorator keeps state on the instance and is easier to introspect, but functools.wraps does not apply. Calling a helper inside the body avoids the indirection but repeats at every call site. If configuration varies per instance, a decorator is the wrong tool: pass it to __init__. For typed wrappers, ParamSpec and TypeVar (3.10+) preserve the signature for type checkers.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Derive the effective call order of stacked authorization, caching, and logging decorators.

Answer

Core answer

Decorator expressions are evaluated top-to-bottom, but each one is applied to the function bottom-to-top. So for

Python
@log
@cache
@authorize
def get_invoice(invoice_id, *, user): ...

the definition-time result is log(cache(authorize(get_invoice))). At call time the outermost wrapper's body runs first, so the effective order is:

log → cache → authorize → body, and the return path unwinds in reverse: body → authorize → cache → log.

That single fact decides everything else: a cache hit returns from the cache wrapper without ever calling authorize, so authorization is skipped entirely on hits.

Worked trace

Python
import functools

def log(fn):
    @functools.wraps(fn)
    def wrapper(*a, **kw):
        print(f"log: enter {fn.__name__}")
        try:
            r = fn(*a, **kw)
            print(f"log: exit {fn.__name__} ok")
            return r
        except Exception as e:
            print(f"log: exit {fn.__name__} raised {type(e).__name__}")
            raise
    return wrapper

def cache(fn):
    store = {}
    @functools.wraps(fn)
    def wrapper(*a, **kw):
        key = (a, tuple(sorted(kw.items())))
        if key in store:
            print("cache: hit"); return store[key]
        print("cache: miss")
        store[key] = fn(*a, **kw)
        return store[key]
    return wrapper

def authorize(fn):
    @functools.wraps(fn)
    def wrapper(*a, **kw):
        if kw.get("user") != "alice":
            print("authz: denied"); raise PermissionError(kw.get("user"))
        print("authz: allowed")
        return fn(*a, **kw)
    return wrapper

@log
@cache
@authorize
def get_invoice(invoice_id, *, user):
    print("body: get_invoice")
    return {"id": invoice_id, "total": 42}

get_invoice(7, user="alice"): first call:

log: enter get_invoice
cache: miss
authz: allowed
body: get_invoice
log: exit get_invoice ok

Same call again: note authorize never runs:

log: enter get_invoice
cache: hit
log: exit get_invoice ok

get_invoice(7, user="bob"): the key includes user, so it misses and authz rejects:

log: enter get_invoice
cache: miss
authz: denied
log: exit get_invoice raised PermissionError

Trade-offs

Cache outside authorize (above): hits are cheap and skip authz, but a revoked or downgraded user keeps receiving cached data until the entry expires. Choose it only when the cached value is identical for every authorized caller and the TTL bounds the staleness you accept.

Authorize outside cache, @authorize @log @cache, runs the authz check on every call, so revocation takes effect immediately, but you pay the check's cost on every request and the cache key must now include the tenant or user, or one user's cached row is served to another. That key-composition bug is the one to watch.

Log placement is the cheap decision: outermost logs denials and cache hits; innermost logs only body executions. Put it outermost if you need an audit trail of rejected requests.

Failure modes and detection

  • Cache hit bypasses authz: detect by asserting the authz counter increments on a repeated call; if it doesn't, the stack is wrong.
  • Cache key omits tenant: detect by calling with two users and asserting distinct results.
  • Exception swallowed by an inner wrapper: the try/except in log re-raises, so the cache wrapper never stores a failed result. Verify no entry is written on the PermissionError path.

Async

With async def, each wrapper must be async and await fn(...). Ordering is unchanged, but a cache hit returns without awaiting, so the event loop never yields inside the stack: a hot cache can starve other tasks if the body is the only suspension point.

functools.lru_cache is the stdlib cache decorator; it keys on the full call signature, so it has the same tenant-key hazard.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Design argument forwarding for a wrapper that consumes one configuration keyword.

Answer

What I'd say first

A wrapper that consumes one keyword has to settle two things before any code: is the keyword consumed at decoration time or call time, and can the wrapped callable already have a parameter of that name? If it is call-time and the name can collide, kwargs.pop("timeout") silently steals the caller's value and the target falls back to its own default: a config knob that never takes effect, with no error. So I read the target's signature at decoration time and raise on collision. That turns a silent misconfiguration into an import-time TypeError.

Python
import functools, inspect

def with_timeout(fn):
    if "timeout" in inspect.signature(fn).parameters:
        raise TypeError(f"{fn.__name__} already declares 'timeout'")

    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        timeout = kwargs.pop("timeout", None)   # consumed here, never forwarded
        return fn(*args, **kwargs)

    return wrapper

functools.wraps copies __name__, __doc__, __dict__ and sets __wrapped__; inspect.signature follows __wrapped__ by default (follow_wrapped=True), so signature(wrapper) reports fn's parameters, not the wrapper's.

Trace

Python
@with_timeout
def fetch(url, *, retries=2):
    return (url, retries)

fetch("http://x", retries=5, timeout=1.5)
  • wrapper receives args=("http://x",), kwargs={"retries": 5, "timeout": 1.5}.
  • kwargs.pop("timeout", None) returns 1.5; kwargs is now {"retries": 5}.
  • fn("http://x", retries=5) returns ("http://x", 5).

The timeout never reaches fetch. Now the collision the guard exists for:

Python
@with_timeout
def slow(url, timeout=30):
    return (url, timeout)
# TypeError: slow already declares 'timeout'  — raised at decoration time

Drop the guard and slow("http://x", timeout=1.5) would pop 1.5, call slow("http://x"), and return ("http://x", 30): the caller's value gone, the default used, nothing logged.

Alternatives and when the choice flips

ApproachSame-named target paramKeyword in signature()Cost
kwargs.pop + decoration-time guardraises at decorationhidden by __wrapped__simplest; needs the guard
Keyword-only wrapper param: def wrapper(*args, timeout=None, **kwargs)silently shadowedhidden by __wrapped__set __signature__ to advertise it
Namespaced name, e.g. _timeoutno collisionvisibleleaks a private-looking name into the public API

Flip to the keyword-only form when the target is third-party and you cannot guarantee its parameter names, but note it shadows rather than raises, so keep the guard if you want the loud failure. Flip to a namespaced name when the keyword must survive a caller's **config splat and you want it visible to introspection tools.

To advertise the consumed keyword while keeping the target's parameters, set __signature__ explicitly (keyword-only params must come last):

Python
sig = inspect.signature(fn)
wrapper.__signature__ = sig.replace(parameters=[
    *sig.parameters.values(),
    inspect.Parameter("timeout", inspect.Parameter.KEYWORD_ONLY, default=None),
])

Failure modes and detection

  • Silent drop on collision. Symptom: a config value that never takes effect, no error. Detected by the inspect.signature guard at import time.
  • Positional pass-through. fetch("http://x", 1.5) puts 1.5 in *args, which is forwarded to the target; the wrapper never sees it. The consumed keyword must be keyword-only by contract, and the docstring should say so.
  • Double delivery. Reading the keyword without popping forwards it to the target, which raises TypeError: unexpected keyword argument unless it declares the name. Pop exactly once.
  • Async targets. A sync wrapper around a coroutine returns an un-awaited coroutine and emits RuntimeWarning: coroutine was never awaited. Use async def wrapper and await fn(...). functools.wraps does not make inspect.iscoroutinefunction(wrapper) true; Python 3.12 added inspect.markcoroutinefunction to mark a sync wrapper for introspection.
  • Consumed but not enforced. Popping timeout and never acting on it is a no-op that hides the caller's intent. The wrapper must actually apply the deadline.

Tests: one call with the keyword, one without (default path), one colliding target that must raise at decoration, and one async target that must be awaited.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

How do closure cells and late binding affect decorator factories?

Answer

Core answer (first 90 seconds). A decorator factory is a function that returns a decorator. Every variable the returned wrapper reads from an enclosing scope lives in a cell, and the wrapper reads that cell at call time, not at definition time. That is late binding, and it decides whether the factory is safe.

Two consequences follow. Factory parameters are safe: each call to prefixer("INFO: ") creates a fresh frame with a fresh cell for prefix, so wrappers from two calls never share state. Anything captured from a frame that outlives one factory call: a loop variable in the enclosing function, or a counter declared outside the decorator: is shared by every wrapper built in that frame, and each wrapper reads the final value. The fix is to bind per-wrapper values at definition time: route them through the factory, bind them as a default on the decorator, or use functools.partial.

Mechanism. CPython compiles a variable to a cell when a nested function references it. The cell is allocated once per frame, so all nested functions created in that frame share it. Reads compile to LOAD_DEREF (read the cell now); writes compile to STORE_DEREF. wrapper.__code__.co_freevars names the cells, and wrapper.__closure__ holds them in that order:

Python
import functools

def prefixer(prefix):
    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            return f"{prefix}{fn(*args, **kwargs)}"
        return wrapper
    return decorator

@prefixer("INFO: ")
def status():
    return "ok"

status()  # 'INFO: ok'

dict(zip(status.__code__.co_freevars,
         (c.cell_contents for c in status.__closure__)))
# {'fn': <function status at 0x...>, 'prefix': 'INFO: '}

There are two cell levels: prefix is a cell in prefixer's frame, fn is a cell in decorator's frame. Both frames are created per call, which is exactly why the factory pattern is safe.

Trace: the bug the factory prevents. Inline the factory into a loop and the cell moves to the enclosing frame:

Python
loggers = []
for lvl in ("INFO", "WARN"):
    def decorator(fn):
        def wrapper(*a, **k):
            return f"{lvl}: {fn(*a, **k)}"
        return wrapper
    loggers.append(decorator)

@loggers[0]
def a(): return "a"
@loggers[1]
def b(): return "b"

a(), b()   # ('WARN: a', 'WARN: b')  -- both read the final lvl

lvl is one cell in the module frame. Iteration 1 stores 'INFO', iteration 2 overwrites it with 'WARN', and both wrappers LOAD_DEREF at call time. Routing through make_logger(lvl) gives each call its own frame and cell, and the output becomes ('INFO: a', 'WARN: b').

Cell lives inShared bySymptomFix
Factory parameterOne wrapper per factory callNone—
Decorator parameter fnOne wrapper per decorationNone—
Enclosing frame, captured in a loopEvery wrapper built in that frameAll wrappers see the last valueCall the factory, or def decorator(fn, lvl=lvl)
Mutable counter outside decoratorEvery function decorated by that decorator instanceCounter counts all calls, not per functionMove calls = 0 inside decorator

Trade-offs. Default-argument binding works because defaults are evaluated at definition time and stored in __defaults__, not in a cell. Bind it on the decorator, not the wrapper: def wrapper(*a, lvl=lvl, **k) makes lvl a keyword-only parameter of the wrapper and collides with a wrapped function that takes lvl=. functools.partial(decorator, lvl=lvl) has the same effect with no signature pollution. A class-based decorator stores config on self in __init__ and reads self.config in __call__ (no cells, so no late binding) at the cost of implementing __get__ for methods and calling functools.update_wrapper for metadata. nonlocal counters are the deliberate use of late binding: the cell is shared, so one count_calls() instance applied to five functions yields one counter of five, not five counters of one.

Failure modes. A shared counter across functions shows up as a total that never matches any single function's call count: assert per-function counts in tests. Loop capture shows up as identical output from differently configured wrappers. calls += 1 on a cell is LOAD_DEREF/BINARY_OP/STORE_DEREF, not atomic, so concurrent wrappers lose increments; use itertools.count() or a lock. In async def wrapper, a cell rebound while the coroutine is suspended is visible on resume: snapshot into a local at coroutine start if you need the value from entry time. Checked on CPython 3.12.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Explain descriptor binding when decorators are applied to methods.

Answer

Core answer (first 90 seconds). A function stored on a class is a descriptor: function implements __get__, and instance.method calls type(instance).__mro__ lookup, finds the function, then invokes function.__get__(instance, type(instance)), which returns a bound method that pre-fills self. So a decorator that returns a plain function keeps method binding for free. A decorator that returns a non-function callable, an instance of a class with __call__ but no __get__, is not a descriptor, so attribute lookup returns it unchanged and self is never injected. The fix is either to return a function, or to give the callable a __get__ that returns types.MethodType(self, obj).

Mechanism. Attribute access on an instance runs type(obj).__mro__ lookup for a data descriptor first, then the instance __dict__, then a non-data descriptor. function is a non-data descriptor, so Counter().inc finds the function on the class and calls its __get__. functools.wraps copies __name__, __qualname__, __doc__, __dict__ and sets __wrapped__, but it does not need to copy __get__: the wrapper is itself a function, so it already has it.

Working case.

Python
import functools

class Counter:
    def __init__(self):
        self.n = 0

    def _log(fn):
        @functools.wraps(fn)
        def wrapper(self, *args, **kwargs):
            return fn(self, *args, **kwargs)
        return wrapper

    @_log
    def inc(self, by=1):
        self.n += by
        return self.n

Counter().inc(2)   # -> 2

Counter.__dict__['inc'] is a function; Counter().inc triggers function.__get__(counter, Counter) → bound method → inc(2) passes self=counter, by=2.

Broken case.

Python
class Callable:
    def __init__(self, fn):
        self.fn = fn
    def __call__(self, *args, **kwargs):
        return self.fn(*args, **kwargs)

class Counter:
    def __init__(self):
        self.n = 0
    @Callable
    def inc(self, by=1):
        self.n += by
        return self.n

Counter().inc(2)
# TypeError: inc() missing 1 required positional argument: 'self'

Trace: Counter().inc finds the Callable instance on the class; Callable has no __get__, so no binding happens and the instance is returned as-is. Calling it with (2) runs Callable.__call__(inst, 2) → self.fn(2) → inc(2), which is missing self.

Fix.

Python
import types

class Callable:
    def __init__(self, fn):
        self.fn = fn
    def __call__(self, *args, **kwargs):
        return self.fn(*args, **kwargs)
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return types.MethodType(self, obj)

Counter().inc → Callable.__get__(inst, counter, Counter) → MethodType(inst, counter); calling (2) invokes inst(counter, 2) → fn(counter, 2) → inc(self=counter, by=2) → returns 2. The obj is None branch matters: Counter.inc (class access) must return the descriptor itself, not a bound method.

Trade-offs. Return a plain function unless you need per-instance state on the wrapper (caches, counters, connection handles), then a descriptor is the right shape, and __get__ is the price. functools.partial is not a descriptor, so partial(fn, x) stored on a class will not bind self either. staticmethod and classmethod are themselves descriptors: @deco above @staticmethod hands the decorator a staticmethod object, which is only callable from Python 3.10 onward; classmethod objects are still not callable, so wrap the underlying function instead.

Failure modes. Missing-self TypeError at first call is the signature of a non-descriptor wrapper. A __get__ that forgets the obj is None branch breaks class-level access and inspect. If the wrapper is a descriptor defined in the class body, __set_name__(owner, name) fires at class creation: use it to record the attribute name rather than hard-coding it. functools.wraps preserves __wrapped__, so inspect.signature still reports the original parameters; a hand-rolled wrapper without it will show (*args, **kwargs) and break introspection-based frameworks.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

How would you preserve semantics when decorating both sync and async callables?

Answer

Core answer (first 90 seconds)

Decide the wrapper's kind at decoration time by asking inspect.iscoroutinefunction(fn), and emit two different wrappers. The async branch is an async def that awaits the original inside try/finally; the sync branch is a plain def. Both get functools.wraps(fn). The one thing you must not do is write a single sync wrapper that calls fn(*args) and returns the coroutine: that silently changes the callable from a coroutine function to a regular function, so inspect.iscoroutinefunction returns False, frameworks that branch on it stop awaiting, and any timing or error capture you put in the wrapper measures coroutine creation, not execution.

Mechanism

Calling an async def function does not run its body. It builds a coroutine object and returns it; the body runs only when something drives it (await, asyncio.run, a Task). So fn(*args) inside a sync wrapper costs a few microseconds and can raise nothing from the body. Errors and cancellation surface later, at the await point, outside your try.

Python
import functools, inspect, time

def timed(fn):
    if inspect.iscoroutinefunction(fn):
        @functools.wraps(fn)
        async def wrapper(*args, **kwargs):
            start = time.perf_counter()
            try:
                return await fn(*args, **kwargs)
            finally:
                print(f"{fn.__name__}: {(time.perf_counter()-start)*1e3:.1f} ms")
        return wrapper

    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return fn(*args, **kwargs)
        finally:
            print(f"{fn.__name__}: {(time.perf_counter()-start)*1e3:.1f} ms")
    return wrapper

functools.wraps copies __name__, __doc__, __dict__, __module__, __qualname__ and sets __wrapped__, so inspect.signature follows through to the original. It does not copy __defaults__ or __kwdefaults__; code that reads those directly sees the wrapper's.

Trace (CPython 3.12, Linux; your numbers will differ):

Python
import asyncio, time
async def work():
    await asyncio.sleep(0.05)
    return 42

t0 = time.perf_counter()
coro = work()                      # body not run
print(f"creation {(time.perf_counter()-t0)*1e6:.1f} us")
print(asyncio.run(coro))           # body runs here
print(f"total {(time.perf_counter()-t0)*1e3:.1f} ms")

Output: creation 1.4 us, 42, total 50.3 ms. A sync wrapper timing work() would report ~1 µs and never see the sleep.

Cancellation and cleanup

asyncio.CancelledError inherits from BaseException since Python 3.8, so except Exception does not swallow it, but except BaseException does. Catch narrowly and re-raise; use finally for timing so it fires on cancellation too. For async resources use contextlib.asynccontextmanager rather than a sync contextmanager, whose __exit__ cannot await.

Typing

Preserve the signature for type checkers with ParamSpec (PEP 612, 3.10+) and overloads:

Python
from typing import Callable, Awaitable, ParamSpec, TypeVar, overload
P = ParamSpec("P"); R = TypeVar("R")

@overload
def timed(fn: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]: ...
@overload
def timed(fn: Callable[P, R]) -> Callable[P, R]: ...

Alternatives and when to use them

  • One wrapper returning fn(*args) unchanged: shortest, works at runtime for both, but loses coroutine-function identity and cannot do async cleanup. Use only for pure pass-through decorators such as logging the call.
  • Two decorators, @timed and @timed_async: explicit, no runtime branch, but callers must pick correctly.
  • inspect.markcoroutinefunction (3.12+) re-marks a sync wrapper as a coroutine function so inspect.iscoroutinefunction returns True: useful when you must keep one wrapper body.

Failure modes

  • Timing only creation: near-zero durations and no body exceptions. Detect by asserting the measured time exceeds a known sleep.
  • Swallowing cancellation: except BaseException or a bare except. Detect with a test that cancels mid-await and asserts CancelledError propagates.
  • iscoroutinefunction returning False after decoration: a framework skips await and you get a "coroutine was never awaited" RuntimeWarning. Detect by asserting inspect.iscoroutinefunction(decorated).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Audit the lifecycle and concurrency risks of a stateful decorator object.

Answer

Assume CPython 3.12, a decorator object shared across threads or asyncio tasks, and both sync and async call sites. The core answer: a stateful decorator object is a singleton by default. Every mutable attribute on it is shared across every call, so it is safe for immutable config or a lock-protected counter, and wrong for per-request state. Audit five phases separately: definition, call entry, body, exit, and async suspension.

Definition time: the decorator object is constructed once at import. __init__ runs once. If you put mutable state in a class attribute, every instance shares it; put it in __init__. Call entry: __call__ runs on every call. An unsynchronized self.calls += 1 is a read-modify-write, not atomic under the GIL. CPython 3.12 switches threads every 5 ms by default (sys.setswitchinterval). Body: the wrapped function runs. If you store request data on self, it leaks across tenants. Exit: cleanup must release locks and reset state. Async suspension: an await inside the body can interleave tasks; a threading.Lock held across await blocks the event loop.

Here is a sync-safe decorator object with a descriptor hook:

Python
import functools, threading, contextvars

_request_id = contextvars.ContextVar("request_id", default=None)

class CountCalls:
    def __init__(self, fn):
        self.fn = fn
        self.calls = 0
        self.lock = threading.Lock()
        functools.update_wrapper(self, fn, assigned=("__name__", "__doc__"), updated=())

    def __call__(self, *args, **kwargs):
        with self.lock:
            self.calls += 1
        return self.fn(*args, **kwargs)

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return functools.partial(self.__call__, obj)

The __get__ matters. Functions are descriptors; plain callable objects are not. Decorate a method with a callable object that lacks __get__, and instance.method returns the decorator object itself. Calling it passes no self, so you get TypeError: method() missing 1 required positional argument: 'self'. The __get__ above returns a partial that injects the instance.

Trace the race. Two threads call an unsynchronized counter:

Python
class Bad:
    def __init__(self, fn):
        self.fn = fn
        self.calls = 0
    def __call__(self, *a, **kw):
        self.calls += 1
        return self.fn(*a, **kw)

Interleaving: T1 reads self.calls -> 0; T2 reads self.calls -> 0; T1 writes 1; T2 writes 1. Final calls is 1, expected 2. With threading.Lock, T2 blocks at with self.lock until T1 exits, final 2. In a hypothetical 8-thread, 100k-increment run, the unsynchronized final value is below 800,000; the exact loss varies.

PhaseWhat runsShared-state riskGuard
Definition__init__ oncemutable class attribute sharedinstance attributes in __init__
Call entry__call__+= racesthreading.Lock sync; asyncio.Lock async
Bodywrapped fnper-request data on self leakscontextvars.ContextVar or explicit arg
Exitcleanuplock not released, state dirtytry/finally, reset method
Async suspensionawaitthreading.Lock across await stalls loopasyncio.Lock only around non-await section

Trade-offs: a closure with nonlocal avoids descriptor issues but is still a singleton if defined once. A class with __call__ gives explicit state and testability. contextvars is per-task, thread-local is per-thread and does not propagate to async tasks. For production counters, use prometheus_client.Counter; it is built for concurrent increments. Do not hand-roll a counter on the decorator unless you need the value inside the process.

Failure modes to test: success, body failure, acquisition failure, cleanup failure, cancellation. For async, cancel a task while it holds asyncio.Lock and assert the lock is released. For pickling, pickle.dumps(decorator) raises TypeError: cannot pickle '_thread.lock' object; define __getstate__/__setstate__ or keep locks out of pickled state. For functools.update_wrapper, pass updated=() so fn.__dict__ does not clobber self.calls.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Compare class decorators with metaclasses and simple registration.

Answer

All three hook class creation, but at different moments and with different blast radius. Registration is an explicit call after the class exists: no magic, no inheritance. A class decorator runs after the class object is built and rebinds the name in the enclosing namespace; its effect is local to that one class. A metaclass runs during creation, before the class object exists, and is inherited by every subclass: that inheritance is both the reason to reach for it and the reason to avoid it. Since Python 3.6, __init_subclass__ (PEP 487) covers most of what people historically used metaclasses for.

Ordering. For class Child(Base, metaclass=Meta) with a decorator, the sequence is fixed:

Python
# Python 3.12
events = []

class Meta(type):
    def __new__(mcls, name, bases, ns, **kw):
        events.append(f"meta.__new__ {name}")
        return super().__new__(mcls, name, bases, ns, **kw)
    def __init__(cls, name, bases, ns, **kw):
        events.append(f"meta.__init__ {name}")
        super().__init__(name, bases, ns, **kw)

class Base(metaclass=Meta):
    def __init_subclass__(cls, **kw):
        super().__init_subclass__(**kw)
        events.append(f"__init_subclass__ {cls.__name__}")

def deco(cls):
    events.append(f"decorator {cls.__name__}")
    return cls

@deco
class Child(Base):
    events.append("body")

print(events)

Output:

['body', 'meta.__new__ Child', '__init_subclass__ Child', 'meta.__init__ Child', 'decorator Child']

The body runs first, into a fresh namespace dict. Meta.__new__ receives that dict and calls type.__new__, which creates the class, fires __set_name__ on every descriptor in the namespace, then calls the parent's __init_subclass__. Meta.__init__ runs next, and the decorator last: by which point the class is fully formed and __set_name__ has already happened.

Comparison.

explicit registrationclass decoratormetaclass
Runsafter definition, on your callafter class object existsduring creation
Inherited by subclassesnonoyes
Can edit the namespace pre-creationnonoyes
Can intercept C()nonoyes, Meta.__call__
Can intercept C.attrnonoyes, Meta.__getattr__
type(C)unchangedunchanged if it returns clsMeta
Costone dict writeone call per decorated classone Python frame per class and per subclass

Failure modes. A decorator that returns something other than the class breaks isinstance, issubclass, super() in subclasses, and pickling: pickle resolves the class by __module__/__qualname__ and needs the name to still point at a class. mypy also types the name as the decorator's return type. Returning cls after registering avoids all of it.

Metaclass conflicts are a hard error: class C(A, B) where type(A) and type(B) are unrelated raises TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases. Overriding Meta.__call__ breaks copy.copy, pickle, and anything that constructs via cls(...).

Registration has a discovery failure: if the module defining the class is never imported, nothing registers. Keying on __name__ collides across modules: use __qualname__ or an explicit key. __init_subclass__ fires for every subclass, including test doubles and mixins; it must call super().__init_subclass__(**kw) to cooperate under multiple inheritance.

Choosing. Explicit registration when the set is small and you control the call sites. A class decorator when the hook is per-class and you want it visible at the definition. __init_subclass__ when you need inheritance propagation without metaclass machinery. A metaclass only when you must change the class before it exists, or intercept instantiation and attribute access on the class itself.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design a retry decorator with sound exception and idempotency boundaries.

Answer

Clarify first. Two questions decide the design: which exceptions are transient, and whether the wrapped operation is safe to run twice. If the operation is a non-idempotent write (a charge, an unkeyed POST), no retry decorator fixes it: you need an idempotency key at the protocol layer, and the decorator should refuse to retry. Assume Python 3.11, a network client, and a caller with its own deadline.

Core answer.

Python
import functools, random, time

RETRYABLE = (ConnectionError, TimeoutError)   # narrow taxonomy

def retry(attempts=4, base=0.1, cap=2.0):
    def deco(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            for attempt in range(1, attempts + 1):
                try:
                    return fn(*args, **kwargs)
                except RETRYABLE:
                    if attempt == attempts:
                        raise          # bare raise: traceback preserved
                    time.sleep(random.uniform(0, min(cap, base * 2 ** (attempt - 1))))
        return wrapper
    return deco

Three boundaries are doing the work. except RETRYABLE catches only the two transient types, so a ValueError from a bad argument fails on attempt 1 instead of being retried four times. raise inside the handler re-raises the current exception with its traceback intact: raise exc would reset it. And because KeyboardInterrupt and asyncio.CancelledError inherit from BaseException, not Exception, neither is caught: cancellation propagates on the first signal.

Trace with attempts=4, base=0.1, cap=2.0:

attempton failure, sleeps
1uniform(0, min(2.0, 0.1·2⁰)) = uniform(0, 0.1)
2uniform(0, 0.2)
3uniform(0, 0.4)
4raises, no sleep

Worst-case sleep is 0.7 s; full jitter halves the expected wait to ~0.35 s and, more importantly, decorrelates 100 clients that all failed at the same instant.

Lifecycle boundaries.

phasewhat runsretry decision
definition timedecorator applied, wrapper builtnone: no I/O
call timewrapper(*args) enterednone
body failureRETRYABLE raisedretry if attempts remain
body exitthe function's own finallyruns on success and failure
cancellationCancelledError / KeyboardInterruptnot caught

Alternatives. tenacity gives the same shape with retry_if_exception_type((ConnectionError, TimeoutError)), wait_exponential(multiplier=1, min=1, max=60), stop_after_attempt(4), and reraise=True: worth the dependency once you want per-call retry budgets or async support. Hand-rolling is ~15 lines and dependency-free, which is fine for one call site. Retry is the wrong tool when the error is deterministic (4xx, schema mismatch) or when the caller already has a deadline: a retry that outlives the caller's timeout just burns capacity.

Failure modes. A retry storm: 100 clients × 4 attempts = 400 requests against a service that is already failing, which is why the cap and jitter matter. A double charge: retrying an unkeyed POST. A swallowed cancellation: catching Exception in an async wrapper delays shutdown until the retry loop finishes. Detect all three with a counter on retries-per-call and a histogram of attempts-to-success; a rising retry rate is the leading indicator before the error rate moves.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

Translate the context-manager protocol into entry, body, and exit steps.

Answer

Core answer. The with statement drives three phases against a context manager. Definition time: the class defines __enter__ and __exit__, and both are looked up on the type, not the instance. An instance attribute named __exit__ is ignored. Call time: mgr = Res() runs; no protocol method fires yet. Entry: the interpreter calls type(mgr).__enter__(mgr) and binds its return value to the as target. Body: your code runs. Exit: the interpreter calls type(mgr).__exit__(mgr, exc_type, exc, tb), passing (None, None, None) when the body finished normally and the sys.exc_info() triple otherwise. A truthy return from __exit__ suppresses the exception and execution resumes after the with block; a falsy return, including the implicit None, lets it propagate. If __enter__ raises, __exit__ never runs.

Python
import sys

class Res:
    def __enter__(self):
        print("enter")
        return self
    def __exit__(self, exc_type, exc, tb):
        print("exit", exc_type.__name__ if exc_type else None)
        return False

with Res() as r:
    print("body", r is not None)

Trace, in interpreter order: Res() constructs the object. with calls Res.__enter__(mgr) → prints enter, returns self, bound to r. Body prints body True. __exit__(None, None, None) → prints exit None, returns False. Output:

enter
body True
exit None

Swap the body for raise ValueError("boom"): __enter__ still prints enter, the body raises, and __exit__(ValueError, ValueError("boom"), <traceback>) prints exit ValueError. Because it returns False, the traceback prints and ValueError: boom propagates. Change the return to True and the same run prints enter / exit ValueError with no traceback: the exception is swallowed.

phasecallargumentsnotes
definitionclass body—__enter__/__exit__ resolved on the type
callRes()—no protocol method fires
entrytype(mgr).__enter__(mgr)nonereturn value is the as target; raising here skips exit
bodyuser code—an exception here becomes the exit triple
exittype(mgr).__exit__(mgr, t, v, tb)(None, None, None) on successtruthy return suppresses

CPython compiles with to a BEFORE_WITH / WITH_EXCEPT_START pair in 3.11+ (SETUP_WITH and WITH_CLEANUP_* in 3.10 and earlier), which is why the exit call is guaranteed even on return, break, or continue out of the body.

Failure modes. If __exit__ itself raises, that new exception replaces the body's exception and the original is attached as __context__: a cleanup bug that hides the real error. Detect it by inspecting __context__/__cause__ or by raising with from. If __enter__ acquires a resource and then raises, nothing releases it; acquire in __enter__ only after the last fallible step, or wrap acquisition in try/except that releases. A bare except inside a @contextmanager generator that returns suppresses the exception silently: the same truthy-return rule, but easy to trigger by accident.

Alternatives. try/finally is the right tool when you don't need a reusable object or an as binding; it has no suppression semantics to get wrong. @contextlib.contextmanager is shorter for one-shot resources but the generator must yield exactly once (a second yield raises RuntimeError: generator didn't stop), and suppression is implicit. A class-based manager is worth it when you need a reusable instance or explicit control of the __exit__ return value. contextlib.ExitStack handles a dynamic number of managers, calling __exit__ in reverse order.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Explain how exceptions are delivered through a generator context manager.

Answer

@contextmanager doesn't build a context-manager class: it wraps your generator in contextlib._GeneratorContextManager. __enter__ is just next(gen): it runs the generator up to the yield and returns the yielded value. __exit__ is where exceptions are delivered. When the with body raised, __exit__(exc_type, exc, tb) calls gen.throw(exc), which raises that exception at the yield expression, inside your generator, as if yield had thrown it. What the generator does next decides the outcome, and __exit__'s return value is the verdict: True suppresses, False lets the original propagate.

Three outcomes:

  • Generator re-raises (or never catches): gen.throw raises the same exception, __exit__ returns False, the exception propagates unchanged.
  • Generator catches and returns (falls off the end): the generator is exhausted, gen.throw raises StopIteration, __exit__ returns True. The exception is silently suppressed.
  • Generator catches and yields again: gen.throw returns a value instead of raising, and __exit__ raises RuntimeError("generator didn't stop after throw()").

Worked trace

Python
from contextlib import contextmanager

@contextmanager
def tx(conn):
    conn.begin()
    try:
        yield conn
    except Exception:
        conn.rollback()
        raise          # re-raise -> propagates
    else:
        conn.commit()

with tx(c) as conn: conn.execute(...) where execute raises OperationalError:

  1. __enter__ → next(gen) → conn.begin(), suspends at yield.
  2. Body raises OperationalError.
  3. __exit__(OperationalError, err, tb) → gen.throw(err).
  4. err is raised at the yield; except Exception catches it, conn.rollback() runs, raise re-raises err.
  5. gen.throw raises err; __exit__ returns False; err propagates to the caller.

Delete the raise and step 5 changes: the generator falls off the end, gen.throw raises StopIteration, __exit__ returns True, and the OperationalError vanishes. The caller sees a clean exit from a failed transaction.

generator after gen.throw(exc)gen.throw raises__exit__ returnscaller sees
re-raises excexcFalseexc
catches, returnsStopIterationTruenothing (suppressed)
catches, yields again— (returns a value)raises RuntimeError("generator didn't stop after throw()")RuntimeError
raises a different exc2exc2False (re-raised)exc2

Failure modes and detection

Silent suppression is the one that bites: an except that logs and then falls off the end turns a failed operation into an apparent success. It is invisible at runtime: nothing is logged as an error and the caller's try/except never fires. Detect it with a test that asserts the body's exception propagates (pytest.raises(OperationalError) around the with), and by reviewing any except inside a @contextmanager generator for a missing raise. The operational cost is a transaction reported as committed when it rolled back.

A second trap: raising StopIteration inside the generator body. Since PEP 479 (Python 3.7+) that is converted to RuntimeError, so it can't be mistaken for normal exhaustion.

When to suppress

Suppression is a contract, not an accident. Return normally (suppress) only when the manager owns the failure and the caller genuinely doesn't need it: the contextlib.suppress(FileNotFoundError) pattern. For resource managers, use try/finally for unconditional cleanup and except ...: raise for conditional cleanup, so the exception always reaches the caller.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

Differentiate single-use, reusable, and reentrant context managers.

Answer

Core answer

Three contracts, distinguished by how many times __enter__ may be called on one object:

  • Single-use: exactly one __enter__ per object, ever. The object is a one-shot token.
  • Reusable: __enter__ may be called again after a matching __exit__ returns. Sequential reuse only; nesting is not supported.
  • Reentrant: __enter__ may be called again while the manager is already active. Nested with on the same object. Reentrant implies reusable; single-use implies neither.

The protocol itself enforces none of this. __enter__/__exit__ are just methods; the contract is what the implementation does with its own state.

Single-use: contextlib.contextmanager

Python
from contextlib import contextmanager

@contextmanager
def cm():
    print("acquire")
    yield 42
    print("release")

m = cm()          # factory call: builds the manager, generator not started
with m:
    print("body")

Trace: cm() returns a _GeneratorContextManager holding an unstarted generator. __enter__ calls next(gen) → prints acquire, suspends at yield, returns 42. Body prints body. __exit__(None, None, None) calls next(gen) again → prints release, the generator returns, StopIteration is caught and __exit__ returns False.

Re-enter the same m:

Python
with m:      # RuntimeError: generator didn't yield
    pass

__enter__ calls next() on an exhausted generator; StopIteration is translated to RuntimeError("generator didn't yield"). The decorated function is reusable, each call builds a fresh manager, but the object is not.

Reusable: fresh state per entry

Python
class Reusable:
    def __enter__(self):
        self.conn = connect()      # re-established on every entry
        return self.conn
    def __exit__(self, *exc):
        self.conn.close()
        self.conn = None
        return False

threading.Lock is the standard-library example: with lock: acquires and releases, and you can do it again. It is reusable but not reentrant: re-acquiring in the same thread blocks forever.

Reentrant: depth counter

Python
class Reentrant:
    def __init__(self):
        self._depth = 0
    def __enter__(self):
        self._depth += 1
        return self
    def __exit__(self, *exc):
        self._depth -= 1
        return False

Nested with r: with r: takes depth 0→1→2, exits 2→1→0. threading.RLock is the stdlib version: the same thread may acquire repeatedly and must release the same number of times.

ContractRe-enter after exitNested entryStdlib exampleRe-entry failure
Single-usenono@contextmanager objectRuntimeError("generator didn't yield")
Reusableyesnothreading.Locknested: deadlock (hangs, no exception)
Reentrantyesyesthreading.RLockunbalanced exit: lock never released

Failure modes and detection

  • Re-entering a single-use manager raises RuntimeError("generator didn't yield"): misleading, because the generator did yield once. Test by entering twice and asserting the raise.
  • Nested entry on a reusable-but-not-reentrant lock deadlocks silently. Detect with a timeout in tests, not by exception.
  • A reentrant manager with an unbalanced __exit__ (more exits than entries) drives the depth counter negative or releases a lock it does not hold. Assert depth returns to 0 after the block.

Async

contextlib.asynccontextmanager produces single-use async managers with the same re-entry error. __aenter__ is awaited, so acquisition can suspend; two tasks entering the same async manager concurrently is a distinct hazard from nesting, and needs an explicit guard.

When not to use each

Default to a factory (@contextmanager function): fresh state per use, nothing to reason about. Reach for a reusable object only when acquisition is expensive enough to amortise (a pooled connection); then __exit__ must fully reset state and you must forbid concurrent use. Reentrancy is worth the bookkeeping only when nesting is a real call pattern: nested transactions via savepoints, or a lock taken by both an outer and an inner function. If nesting never happens, a depth counter is dead weight that hides bugs.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How would you roll back resources acquired before `__enter__` fails?

Answer

Short answer. with never calls __exit__ when __enter__ raises, so anything __enter__ acquired before the raise leaks. Fix it inside __enter__: release in an except, or push each acquisition onto a contextlib.ExitStack and call stack.close() in the handler.

Why. CPython compiles with EXPR as v: BODY to roughly:

Python
mgr = EXPR
enter = type(mgr).__enter__
exit = type(mgr).__exit__
v = enter(mgr)          # if this raises, exit is never called
try:
    BODY
except BaseException:
    if not exit(mgr, *sys.exc_info()):
        raise
else:
    exit(mgr, None, None, None)

exit is only invoked after enter returns. A raise inside __enter__ propagates straight out of the with; the manager is left half-built.

Trace. Pool of size 1, __enter__ acquires a connection then a lock that is unavailable:

Python
class TwoResources:
    def __enter__(self):
        self.conn = self.pool.acquire()          # pool.conns == [c]
        self.lock = self.lock_manager.acquire()  # raises RuntimeError
        return self
    def __exit__(self, *exc):
        self.pool.release(self.conn)
        return False

pool.acquire() appends c, so pool.conns == [c]. lock_manager.acquire() raises. __exit__ is never called. pool.conns is still [c]: one connection gone for the process lifetime. Repeat under load and the pool drains to zero, and every later acquire() blocks or raises.

Fix.

Python
import contextlib

class TwoResources:
    def __enter__(self):
        self._stack = contextlib.ExitStack()
        try:
            self.conn = self._stack.enter_context(self.pool.connection())
            self.lock = self._stack.enter_context(self.lock_manager.lock())
        except BaseException:
            self._stack.close()   # LIFO unwind of what was pushed
            raise
        return self

    def __exit__(self, *exc):
        return self._stack.__exit__(*exc)

enter_context calls the resource's __enter__ and registers its __exit__ as a callback. close() runs those callbacks in reverse order, so the connection is released when the lock acquire fails. Catch BaseException, not Exception, so KeyboardInterrupt and asyncio.CancelledError also roll back.

Alternatives.

approachrolls back partial __enter__when to use
nested with in the bodyyes: each __enter__ is atomiccaller can see and order the resources
manual try/except releasing eachyesone or two resources
ExitStack + close() in exceptyesN resources, LIFO, cleanup errors chained
bare acquire in __enter__nonever

Failure modes.

  • Leak with no error: the with body never runs, so nothing looks wrong. Detect with a pool gauge (len(pool.conns)), or python -X dev, which turns unclosed files and sockets into ResourceWarning.
  • Cleanup raising during rollback: ExitStack.close() keeps running the remaining callbacks, but the new exception replaces the original; inspect __context__ to see both.
  • Reuse after partial failure: set self.conn = None after release so a second close() is a no-op.

Don't reach for ExitStack when the manager owns exactly one resource: a try/except around the acquire is shorter and clearer.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Compare native resource managers with `closing` and `aclosing` adapters.

Answer

Core answer

contextlib.closing and contextlib.aclosing are adapters: they give you with / async with syntax over an object that has a close() (or aclose()) method but no __enter__/__exit__ (or __aenter__/__aexit__). A native context manager owns its own lifecycle: __exit__ can commit, roll back, release a lock, return a connection to a pool, or suppress an exception. The adapters do exactly one thing: call close() (sync) or await aclose() (async) on exit, and they never suppress exceptions. So the rule is: use the native protocol when the object has one; reach for an adapter only when the object's documented API is just close()/aclose().

closing has been in contextlib since Python 2.5. aclosing is newer: Python 3.10, and exists because async generators need deterministic cleanup.

The mechanism

closing(thing) returns a context manager whose __enter__ returns thing itself (it calls nothing on entry) and whose __exit__ calls thing.close() and returns None. aclosing(thing) is the same shape, but __aexit__ does await thing.aclose().

Python
import socket
from contextlib import closing

with closing(socket.socket()) as s:   # socket has close(), no __enter__
    s.connect(("example.com", 80))
# s.close() runs here, even if connect() raised

Async:

Python
import asyncio
from contextlib import aclosing

async def gen():
    try:
        yield 1
        yield 2
    finally:
        print("cleanup")

async def main():
    async with aclosing(gen()) as g:
        async for x in g:
            print(x)
            break

asyncio.run(main())

Trace: gen() builds the async generator. aclosing(...).__aenter__ returns it as g. async for calls __anext__, the body runs to yield 1, print(x) prints 1. break leaves the loop, so __aexit__ runs await g.aclose(), which throws GeneratorExit at the yield, the finally runs and prints cleanup. Output is exactly:

1
cleanup

Without aclosing, the generator is closed later by the event loop's async-generator finalizer (loop.shutdown_asyncgens, run at asyncio.run teardown), so cleanup prints after main returns: same text, wrong time, and if the generator holds a connection or lock, it is held longer than the block.

Comparison

native with / async withclosingaclosing
Calls on exit__exit__ / __aexit__close()await aclose()
Yields__enter__'s returnthe object itselfthe object itself
Suppresses exceptionsif __exit__ returns truthynono
Asyncasync withnoyes
Since—2.53.10

Failure modes

  • Wrapping a native context manager in closing skips __exit__. sqlite3.Connection.__exit__ commits on success and rolls back on exception; close() does neither. with closing(conn): conn.execute("INSERT ...") silently loses the insert. Detection: rows missing after the block, no error raised.
  • closing on an async resource: close() returns a coroutine that is never awaited. RuntimeWarning: coroutine ... was never awaited, and the resource leaks.
  • aclosing on a sync object: AttributeError: ... has no attribute 'aclose' at exit, after the body already ran.

When not to use them

If the object has __enter__/__exit__, use it: the adapter is strictly less capable. Adapters are for the documented close()-only case: sockets, some DB-API connections, file-like objects from third-party libraries, and async generators.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Use `nullcontext` to model optional ownership without duplicating a code block.

Answer

contextlib.nullcontext(enter_result=None) is a context manager whose __enter__ returns the value you passed in (default None) and whose __exit__ does nothing. It exists so one with body can serve both "I created this resource" and "the caller owns it" without an if around the body.

Python
import contextlib

class Conn:
    def __init__(self, name): self.name = name
    def __enter__(self):  print(f"open {self.name}");  return self
    def __exit__(self, *exc): print(f"close {self.name}"); return False

def run(conn=None):
    cm = contextlib.nullcontext(conn) if conn is not None else Conn("local")
    with cm as c:
        print(f"using {c.name}")

run()                 # local branch
run(Conn("caller"))   # caller-owned branch

Trace, the way the interpreter runs it:

  • run(): conn is None, so cm = Conn("local"). with cm as c calls Conn.__enter__ → prints open local, binds c to the Conn. Body prints using local. Exit calls Conn.__exit__ → prints close local.
  • run(Conn("caller")): the argument is constructed first (__init__ prints nothing). conn is not None, so cm = nullcontext(conn). nullcontext.__enter__ returns conn: it does not call Conn.__enter__ on it. Body prints using caller. nullcontext.__exit__ is a no-op.

Output:

open local
using local
close local
using caller

The second run never prints open caller or close caller. That is the whole point: nullcontext transfers no ownership and performs no setup or teardown on the object it wraps. The caller's Conn is used and left exactly as it was found.

What it is not. nullcontext(x) is not "conditionally enter x". If the caller-owned object is itself a context manager that needs __enter__ (a transaction, a lock, a tempdir), wrapping it in nullcontext silently skips that setup. Use contextlib.ExitStack instead, which lets you push a variable number of managers:

Python
with contextlib.ExitStack() as stack:
    c = stack.enter_context(conn) if conn is not None else stack.enter_context(connect_db())

For async managers the equivalent is contextlib.AsyncExitStack. nullcontext itself implements __aenter__/__aexit__ (since 3.10), so async with nullcontext(x) as v works, but it still won't enter x. And contextlib.suppress is a different tool: it swallows listed exceptions; it has nothing to do with ownership.

Failure modes.

  • Closing a caller-owned resource. If the body ends with c.close() or a finally that closes, the caller's next use raises ValueError: I/O operation on closed file (or the driver's equivalent). Detection: the caller's subsequent call fails, not yours.
  • Assuming setup happened. nullcontext(txn) skips txn.__enter__, so writes run outside the transaction and are never committed. Detection: missing rows after the block, or "no transaction in progress" from the driver.
  • Reuse asymmetry. nullcontext is stateless, so the same instance can be entered repeatedly and nested. A real manager usually cannot: hoisting cm = open(path) out of a loop gives ValueError: I/O operation on closed file on iteration two. nullcontext won't warn you about the difference.

Cost and when not to use it. __enter__ returns a stored attribute and __exit__ returns None; both are O(1) with no allocation beyond the instance. Reach for it when exactly one branch has nothing to manage. If both branches have real managers, or you need to register cleanup callbacks conditionally, ExitStack is the right tool: nullcontext will quietly skip the setup you were relying on.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

When does `contextlib.suppress` improve code, and when does it hide defects?

Answer

Short answer: suppress is right when the exception is expected in normal operation, the body is a single operation, and continuing leaves state consistent. It hides defects the moment any of those three fails: most often when the body is a block of work or the type is Exception.

Mechanism. contextlib.suppress(*exceptions) is a context manager. Its __exit__ returns True when issubclass(exctype, self._exceptions), and a truthy return from __exit__ is what tells the with statement to swallow the exception and resume after the block. That is the whole behaviour: it is try/except E: pass with identical scoping. No logging, no re-raise.

Python
import contextlib, os

with contextlib.suppress(FileNotFoundError):
    os.remove("cache.lock")
print("continuing")

Trace it:

  1. __enter__ runs and returns None.
  2. os.remove raises FileNotFoundError.
  3. The with machinery calls __exit__(FileNotFoundError, exc, tb).
  4. issubclass(FileNotFoundError, (FileNotFoundError,)) is True, so __exit__ returns True.
  5. The exception is suppressed; execution resumes at print("continuing").

Change the raised type to PermissionError and step 4 becomes False, __exit__ returns None, and the exception propagates. Only the listed types are caught: that precision is the point.

When it hides defects. The failure is a body that does more than one thing, or a type that is too broad:

Python
with contextlib.suppress(Exception):
    data = json.loads(payload)
    total = data["items"][0]["price"] * qty
    write_report(total)

If payload lacks "items", the KeyError is swallowed, write_report never runs, total is never bound, and the function returns normally. The caller sees success and a missing report. Detection: the function returns None where a value is expected, or the output file is absent. Both silent unless you log. A counter or a logging.warning in an explicit except is the fix.

Deciding criteria.

Questionsuppressexplicit except
Expected in normal operation?yesno
Body is one operation?yesno
Continuing leaves state consistent?yesno
Need to log, retry, or re-raise?noyes

Alternatives. try/except E: pass is the same semantics with room for a comment. try/except E as e: log(...) when you need observability. When the API offers it, avoid the exception entirely: os.remove(path, missing_ok=True) (3.8+) or dict.get. Nothing to suppress.

Failure modes.

  • suppress(Exception) catches programming bugs (KeyError, TypeError, AttributeError) alongside expected ones. Detect by asserting the post-condition after the block.
  • A multi-statement body leaves partial work. Keep the block to one call.
  • suppress(BaseException) swallows KeyboardInterrupt and SystemExit. Since Python 3.8 asyncio.CancelledError derives from BaseException, so suppress(Exception) does not swallow task cancellation, but suppress(BaseException) does. Never suppress BaseException.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

Define a narrow and reviewable exception-suppression contract.

Answer

The contract, stated first. __exit__ suppresses the active exception only when it returns a truthy value, and only for the exception types it names explicitly. Everything else propagates with its original traceback. Assumptions: CPython 3.12, the with statement, sync and async variants.

Mechanism. When the body of a with block raises, the interpreter calls __exit__(exc_type, exc, tb) with the exception triple. A truthy return discards the exception and execution resumes at the first statement after the block. A falsy return (False, None, 0) lets it propagate. On normal completion __exit__ is called with (None, None, None) and the return value is ignored, because there is nothing to suppress. The async form is identical except the interpreter awaits __aexit__(exc_type, exc, tb).

Python
# Python 3.12
class SuppressNotFound:
    def __init__(self, path: str) -> None:
        self.path = path
        self.suppressed: BaseException | None = None

    def __enter__(self) -> "SuppressNotFound":
        return self

    def __exit__(self, exc_type, exc, tb) -> bool:
        if exc_type is None:
            return False
        if issubclass(exc_type, FileNotFoundError):
            self.suppressed = exc
            return True
        return False

Trace. with SuppressNotFound("cfg.toml") as cm: open(cm.path):

  1. __enter__ returns the manager; cm is bound to it.
  2. open("cfg.toml") raises FileNotFoundError.
  3. The interpreter calls __exit__(FileNotFoundError, err, tb).
  4. exc_type is None is false; issubclass(FileNotFoundError, FileNotFoundError) is true, so it stores err and returns True.
  5. The with swallows the exception; the statement after the block runs, and cm.suppressed holds the exception object.

If the body raised PermissionError instead, step 4's issubclass is false, __exit__ returns False, and the exception propagates with its original traceback.

__exit__ returnsexception activeresult
None / Falseyespropagates
Trueyessuppressed; execution continues after with
anythingnoignored

Alternatives and when suppression is wrong. contextlib.suppress(FileNotFoundError) is the stdlib version of exactly this contract: it returns True only for the types you list. Reach for it when you don't need to record the exception; write a class when you need to inspect, log, or condition suppression on state. Suppress only when the absence is a valid state the caller already handles. If the caller must distinguish "file missing" from "file unreadable", don't suppress: re-raise or translate to a domain error.

Failure modes.

  • return self from __exit__ is truthy and suppresses everything. It appears whenever someone adds chaining to a manager.
  • Catching BaseException and returning True swallows KeyboardInterrupt and SystemExit.
  • Async: asyncio.CancelledError is a BaseException subclass since Python 3.8. An __aexit__ that returns True unconditionally swallows cancellation, so Task.cancel() and asyncio.timeout() never take effect and the task runs to completion.

Detection. One test asserts the intended exception does not escape the block; a second asserts an unexpected one does, via pytest.raises. For async managers, a third cancels the task and asserts CancelledError propagates.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design dynamic all-or-nothing resource acquisition with `ExitStack`.

Answer

Core answer. ExitStack is what you reach for when the number of resources isn't known until runtime but acquisition still has to be all-or-nothing. You enter each resource with stack.enter_context(cm): that calls cm.__enter__() and pushes cm.__exit__ onto an internal list. If a later __enter__ raises, the stack's own __exit__ unwinds everything already pushed, in LIFO order: that is the rollback. When acquisition succeeds and you want to hand ownership to a caller, stack.pop_all() returns a new ExitStack holding the callbacks and empties the original, so the with block that created it no longer owns anything.

Python
# Python 3.11
from contextlib import ExitStack

class Conn:
    def __init__(self, name, fail=False):
        self.name, self.fail = name, fail
    def __enter__(self):
        if self.fail:
            raise RuntimeError(f"{self.name} refused")
        print(f"open {self.name}")
        return self
    def __exit__(self, *exc):
        print(f"close {self.name}")
        return False

def acquire_all(specs):
    with ExitStack() as stack:
        conns = [stack.enter_context(Conn(n, f)) for n, f in specs]
        return stack.pop_all(), conns   # transfer ownership to caller

Trace of acquire_all([("db", False), ("cache", False), ("queue", True)]):

  1. enter_context(Conn("db")) → prints open db, pushes Conn("db").__exit__.
  2. enter_context(Conn("cache")) → prints open cache, pushes its __exit__.
  3. enter_context(Conn("queue")) → __enter__ raises RuntimeError("queue refused"); nothing is pushed for queue.
  4. The exception leaves the comprehension and the with body, so ExitStack.__exit__ runs: pops LIFO → close cache, then close db.
  5. RuntimeError: queue refused propagates to the caller.

Output: open db, open cache, close cache, close db, then the RuntimeError. Two resources opened, both closed, none leaked: that is the all-or-nothing property, and it comes purely from LIFO unwinding of what was actually pushed.

Trade-offs.

approachresource countrollback on partial failureownership transfer
nested withfixed at write timeautomatic, only for levels writtenno
try/finallyanymanual: you track what succeededmanual
ExitStackany, decided at runtimeautomatic, LIFOpop_all()

Use nested with when the count is small and fixed; it reads better and needs no import. Use ExitStack only when the count is dynamic or you need to hand a bundle of live resources to another function. For async resources you need AsyncExitStack, which awaits __aexit__; plain ExitStack will not.

Failure modes.

  • stack.callback(f) calls f() with no arguments at unwind. If f needs exception details, use stack.push(cm) with an __exit__(exc_type, exc, tb) signature instead. Passing a three-argument function to callback raises TypeError during unwind, and because ExitStack keeps unwinding, that TypeError becomes the exception that propagates, with the original chained on __context__.
  • A cleanup that raises mid-unwind does not stop the rest: remaining callbacks still run, and the last exception raised wins. Detect this by asserting your connection-pool count returns to baseline after the test, not just that the test passed.
  • pop_all() transfers ownership; if the returned stack is never closed, every resource leaks. Assert fd or pool counts in tests to catch it.

Test the four paths explicitly: success, body raising after acquisition, an __enter__ raising mid-list, and a cleanup raising during unwind.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Explain exception replacement and suppression during ExitStack unwinding.

Answer

The 90-second answer. ExitStack holds a LIFO list of exit callbacks. When the with body raises, ExitStack.__exit__(exc_type, exc, tb) pops callbacks one at a time and calls each with the current exception triple, not the original one. Two things mutate that triple mid-unwind:

  • Suppression. A callback that returns a truthy value sets suppressed_exc = True and resets the triple to (None, None, None). Every callback registered before it (which runs after it, because of LIFO) then sees no exception at all.
  • Replacement. A callback that raises makes its own exception the current triple, sets that exception's __context__ to the one it displaced, and the remaining callbacks see the new one.

ExitStack.__exit__ returns received_exc and suppressed_exc: true only if an exception arrived and at least one callback suppressed it. If any callback raised, that exception is re-raised at the end, even if an earlier callback had suppressed the original.

Worked trace (CPython 3.12; ExitStack is 3.3+, AsyncExitStack 3.7+):

Python
import contextlib

def note(name):
    def cb(exc_type, exc, tb):
        print(f"{name}: {exc_type.__name__ if exc_type else None}")
        return False
    return cb

def swallow(exc_type, exc, tb):
    print(f"swallow: {exc_type.__name__}")
    return True

def blow_up(exc_type, exc, tb):
    raise RuntimeError("cleanup failed")
Python
# 1. plain propagation
with contextlib.ExitStack() as stack:
    stack.push(note("outer"))
    stack.push(note("inner"))
    raise ValueError("body")
# inner: ValueError
# outer: ValueError
# ValueError propagates (__exit__ returns False)

# 2. suppression
with contextlib.ExitStack() as stack:
    stack.push(note("outer"))
    stack.push(swallow)
    raise ValueError("body")
# swallow: ValueError
# outer: None          <- triple was cleared
# nothing propagates (__exit__ returns True)

# 3. replacement
with contextlib.ExitStack() as stack:
    stack.push(note("outer"))
    stack.push(blow_up)
    raise ValueError("body")
# outer: RuntimeError  <- outer sees the new exception
# RuntimeError propagates; its __context__ is the ValueError, so the
# traceback reads "During handling of the above exception, another
# exception occurred"

# 4. suppression then replacement
with contextlib.ExitStack() as stack:
    stack.push(blow_up)
    stack.push(swallow)
    raise ValueError("body")
# swallow: ValueError
# RuntimeError propagates — the later raise undoes the suppression

Trade-offs. ExitStack beats nested with when the number of resources is dynamic (a loop opening connections) or when ownership must move: pop_all() hands the callbacks to a fresh stack without unwinding, which is how you commit a transaction; close() unwinds with no exception. push(cb) gives you suppression control because the return value is honoured; stack.callback(fn) wraps fn and discards its return value, so it can never suppress: use it for fire-and-forget cleanup. contextlib.suppress(FileNotFoundError) is the narrow tool when you want exactly one exception type swallowed. AsyncExitStack applies identical rules but awaits async callbacks; sync callbacks pushed onto it are still called directly.

Failure modes. A cleanup callback that raises replaces the body exception, so on-call sees RuntimeError: cleanup failed and the root-cause ValueError only in the __context__ chain: detect it by logging both exc and exc.__context__ at the unwind boundary, and by asserting in tests that the body exception is what escapes. A callback that accidentally returns a truthy value (e.g. return self.flush()) silently swallows the body exception; the fix is stack.callback for anything not meant to suppress. Because suppression clears the triple, an outer cleanup that decides rollback-vs-commit from exc_type will take the commit path after an inner suppression: order your registrations so the decision-maker runs first. Under AsyncExitStack, a cancellation arriving during unwinding is itself an exception triple, and a second cancellation inside an awaited cleanup replaces it, so guard awaited cleanups with asyncio.shield or a timeout.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Manage mixed synchronous and asynchronous resources with `AsyncExitStack`.

Answer

What a strong candidate says first

AsyncExitStack is ExitStack for the mixed case: some resources clean up with a coroutine (await session.close(), await conn.release()), others with a plain call (file.close(), lock.release()), and you acquire them dynamically. In a loop, conditionally, or in a helper that hands the stack back to its caller. Nested async with can't express a dynamic set; ExitStack can't await; AsyncExitStack does both, unwinding in LIFO order.

The API splits by resource kind

resourcecallregisters
async CMawait stack.enter_async_context(cm)cm.__aexit__
sync CMstack.enter_context(cm)cm.__exit__
async cleanup fnstack.push_async_callback(fn, *a)await fn(*a)
async __aexit__-shaped fnstack.push_async_exit(fn)await fn(et, e, tb)
sync cleanup fnstack.callback(fn, *a)fn(*a)
sync __exit__-shaped fnstack.push(fn)fn(et, e, tb)

AsyncExitStack is itself an async CM: async with AsyncExitStack() as stack: returns the stack from __aenter__ and calls await stack.aclose() from __aexit__. aclose() is the manual unwind; pop_all() moves the pending callbacks to a fresh stack without unwinding, which is how you return a stack from a helper.

Mechanism

Registration order is acquisition order; unwind is LIFO, matching nested with. __aexit__ pops callbacks one at a time and calls each with the current exception triple. Two details are checkable in contextlib.py:

  1. If a cleanup raises, the loop does not stop. It records the new exception, chains it onto the old one via __context__, and keeps unwinding the rest, then re-raises. One failing cleanup does not strand the others.
  2. If a cleanup suppresses (returns true), the triple passed to the remaining callbacks is cleared to (None, None, None).

Worked example

Python
import asyncio, threading
from contextlib import AsyncExitStack

async def handle(job_id, pool):
    async with AsyncExitStack() as stack:
        conn = await stack.enter_async_context(pool.acquire())       # (1) async CM
        log  = stack.enter_context(open(f"/tmp/{job_id}.log", "a"))  # (2) sync CM
        lock = stack.enter_context(threading.Lock())                 # (3) sync CM
        stack.push_async_callback(conn.execute,                      # (4) async fn
                                  "DELETE FROM tmp WHERE id=%s", job_id)
        stack.callback(log.write, "done\n")                          # (5) sync fn
        await conn.execute("INSERT INTO tmp VALUES (%s)", job_id)
    return "ok"

Normal exit, LIFO: (5) log.write("done\n"), (4) await conn.execute("DELETE ..."), (3) lock.__exit__, (2) log.close(), (1) conn.__aexit__ returns the connection to the pool. If the body raises, __aexit__ is called with the triple and every callback sees it; if (4) raises, (3)(2)(1) still run and the original exception is re-raised with the cleanup exception chained.

Failure modes

  • Missing await on aclose() or enter_async_context: you get a coroutine object, nothing is registered, nothing is cleaned up. Detect via RuntimeWarning: coroutine ... was never awaited or a leaked-connection gauge.
  • Cancellation during unwind: aclose catches CancelledError from a callback like any other exception and continues, so the remaining cleanups run and the cancellation is re-raised at the end. If a cleanup must complete (flush a buffer, release a lock), shield it or bound it with a timeout.
  • pop_all() without closing the returned stack leaks every resource it holds.

Alternatives

Nested async with for a fixed, small set. ExitStack when nothing is async. Manual try/finally when ordering is trivial. AsyncExitStack when the set is dynamic or mixed.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

Design commit, rollback, and exception chaining for a transaction manager.

Answer

What I'd say first. Assume a Python 3.11 service on psycopg2 2.9 against PostgreSQL, autocommit off. The manager is a context manager: commit only when the body returns normally, roll back when it raises, and never let the rollback path swallow the exception that caused it. __exit__ returning False (or None) propagates the original; returning True suppresses it, which is almost always wrong here.

Python
import psycopg2  # 2.9.9, Python 3.11

class Transaction:
    def __init__(self, conn):
        self.conn = conn

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is None:
            try:
                self.conn.commit()
            except Exception:
                self.conn.rollback()   # commit failed: state uncertain
                raise
            return False
        try:
            self.conn.rollback()
        except Exception as rb_err:
            raise TransactionError("rollback failed") from exc_val
        return False                   # propagate the body's exception

Worked trace. Transfer $100 from A to B; B's balance would go negative.

stepactionstate
1with Transaction(conn):__enter__ returns self; psycopg2 opens a transaction on first execute
2UPDATE accounts SET bal = bal - 100 WHERE id='A'rowcount 1, txn open
3UPDATE accounts SET bal = bal + 100 WHERE id='B'raises psycopg2.errors.CheckViolation
4__exit__(CheckViolation, err, tb)exc_type not None → conn.rollback(); both updates discarded
5return FalseCheckViolation propagates to caller

Net: A unchanged, exception visible. The anti-pattern try: transfer() finally: conn.commit() runs commit at step 3's unwind, so the −100 is committed and the +100 never applied: money vanishes.

Trade-offs.

choicewhen it winscost
commit on clean exitshort request-scoped unitscommit point is implicit; hard to interleave two units
explicit conn.commit()long-lived connections, multiple unitscaller must remember it; easy to leak an open txn
return True (suppress)manager itself recovered (retry succeeded)caller cannot tell failure happened
return False (propagate)defaultcaller must handle the exception
ROLLBACK TO SAVEPOINT sp1nested/partial worksavepoint per nesting level; not free

Nested work. Wrap the inner unit in SAVEPOINT sp1 / ROLLBACK TO SAVEPOINT sp1 / RELEASE SAVEPOINT sp1 so an inner failure discards only the inner writes and the outer transaction can still commit. A full rollback() here would throw away the outer work too.

Failure modes.

  • Commit in finally: commits failed work (trace above).
  • return True after rollback: caller sees success, data is gone.
  • Rollback itself fails (connection dropped): PostgreSQL leaves the session in an aborted transaction. Further commands fail with SQLSTATE 25P02, "current transaction is aborted". Chain the original with raise TransactionError(...) from exc_val so __cause__ keeps the body exception; without from, Python still sets __context__, but from makes the link explicit and from None would erase it.
  • Cancellation mid-body: the with block still runs __exit__, so rollback fires; test it.

Tests: success, body failure, acquisition failure, rollback failure, cancellation. Assert the original exception type survives and that no partial write is visible after rollback.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Why does a lock context manager prevent leaks but not deadlocks or races?

Answer

What I'd say first

A with lock: block guarantees the lock is released on every exit path (normal return, a return inside the body, or any exception) because the with statement compiles to a try/finally around lock.__exit__. That kills one class of bug: the leaked lock, where a thread acquires and never releases, so every other thread blocks forever. It does nothing about deadlock or races, because those are properties of how many locks you hold and in what order and what the critical section actually protects, not of whether release happens.

Mechanism

In CPython 3.12, with lock: calls lock.__enter__() (which calls acquire()) and, on the way out, lock.__exit__(exc_type, exc, tb) (which calls release()). The compiler emits the __exit__ call in a finally block, so it runs during exception unwinding, before the exception propagates. That is the entire leak guarantee.

Python
import threading
lock = threading.Lock()

def transfer(a, b, amount):
    with lock:               # __enter__ -> acquire()
        a.balance -= amount  # if this raises...
        b.balance += amount  # ...__exit__ still runs
    # __exit__ -> release() on every path

Trace: a thread calls transfer; __enter__ acquires; a.balance -= amount raises AttributeError; the finally runs __exit__, which releases; the exception then propagates. No leak.

Why it doesn't stop deadlock

Deadlock is about the order of acquisition across threads, not release. Two threads each hold one lock and wait for the other's:

Python
lock_a, lock_b = threading.Lock(), threading.Lock()

def t1():
    with lock_a:
        with lock_b: pass

def t2():
    with lock_b:
        with lock_a: pass

Both with blocks release correctly if they ever exit, but neither does. The context manager is doing its job; the program is still stuck. Same for self-deadlock: threading.Lock is not reentrant, so with lock: with lock: blocks the same thread forever. Use threading.RLock if you need reentrancy.

Why it doesn't stop races

A lock serializes; it does not define the invariant. If two locks guard one invariant, or you read outside the lock and write inside, the race survives:

Python
lock_x, lock_y = threading.Lock(), threading.Lock()

def inc():
    with lock_x:
        v = counter.value      # read under lock_x
    with lock_y:
        counter.value = v + 1  # write under lock_y

Two threads interleave and one increment is lost. Both with blocks released cleanly.

What the context manager does and does not cover

Propertywith lock: guarantees it?
Release on return or exceptionYes
Release on KeyboardInterrupt / SystemExitYes: BaseException unwinds through finally
No deadlockNo: ordering is yours
No raceNo: invariant scoping is yours
No blocking I/O under lockNo

Trade-offs and when not to use it

  • try/finally with explicit acquire() / release() is equivalent but noisier; reach for it only when you need acquire(timeout=...) or acquire(blocking=False) to fail fast instead of hanging.
  • In asyncio, threading.Lock blocks the event-loop thread; use asyncio.Lock with async with.
  • If the invariant is a single counter, an atomic or a single-threaded actor model removes the lock entirely.

Failure modes and detection

  • Deadlock: dump stacks with faulthandler.dump_traceback_later(10, exit=True) or py-spy dump --pid <pid>; look for two threads each blocked in acquire on the lock the other holds.
  • Blocking I/O under lock: a 20 ms DB call inside the critical section (illustrative) turns a 5-thread pool's p99 from roughly 20 ms to roughly 100 ms; measure with lock-hold-time histograms.
  • Races: stress the invariant with N threads and assert the final value; run under ThreadSanitizer in C/C++ or Go's -race.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

Choose between a decorator and context manager for a scoped production concern.

Answer

Decision rule. If the concern's scope is exactly one call and every call needs it, use a decorator. If the scope is a region inside a function, or only some call sites need it, use a context manager. The tie-breaker is whether the concern has to re-run the body: retry and circuit-breaking re-invoke, so they need a decorator; acquire/release pairs need a context manager.

Assumptions. Python 3.12, a sync request handler, psycopg 3, a 20-connection pool, and a handler that does non-DB work around a short DB write.

The concern, scoped. You want a transaction with a 2 s statement timeout around the order insert only, not around the payment call that follows it.

Python
# Python 3.12
import contextlib

@contextlib.contextmanager
def tx(conn, timeout_ms=2000):
    with conn.transaction():
        with conn.cursor() as cur:
            cur.execute("SET LOCAL statement_timeout = %s", (timeout_ms,))
            yield cur

def handle_order(conn, order):
    payload = parse(order)          # 5 ms, no DB
    with tx(conn):                  # scope: the insert only
        insert_order(conn, payload) # 12 ms
    charge_card(payload)            # 180 ms, external HTTP
    return payload

The decorator version binds the same transaction to the whole function:

Python
def transactional(fn):
    @functools.wraps(fn)
    def wrapper(conn, *a, **kw):
        with conn.transaction():
            return fn(conn, *a, **kw)
    return wrapper

Trace. The decorator enters conn.transaction() before parse and exits after charge_card returns, so the transaction is open for 5 + 12 + 180 = 197 ms. The context manager opens it for 12 ms. Row locks on orders and the pool checkout are held for the same interval: at 197 ms a connection serves ~5.1 req/s, so the 20-connection pool ceilings at ~100 req/s; at 12 ms it serves ~83 req/s and the pool ceilings at ~1,600 req/s. (Illustrative arithmetic, not a benchmark.)

decoratorcontext manager
scopewhole function, fixed at definitionexplicit block at the call site
visibilityhidden from the callervisible in the body
reuseevery call, no opt-outopt-in per site
asyncneeds an async-aware wrappercontextlib.asynccontextmanager

Failure modes. charge_card raises after the insert. With the decorator the exception unwinds through the wrapper, conn.transaction() rolls back the insert, but the card may already be charged, leaving money taken and no order row. Detect it by reconciling the payment provider's ledger against orders nightly and alerting on any mismatch. With the context manager the insert commits before charge_card runs, so the same failure leaves an order stuck in pending_payment; detect it as rows older than 15 minutes in that state. The context manager does not remove the failure, it makes the boundary explicit so you can pick which inconsistency you can reconcile.

Async is the second trap. A sync transactional wrapping async def handle_order returns the coroutine without awaiting it, so the with block exits before any query runs and nothing is transactional. Use contextlib.asynccontextmanager and an async def wrapper, or keep the with inline.

When the decorator wins. Retry cannot be expressed as a context manager: you cannot re-enter a with block, and the body has to run again. @retry(attempts=3, base_delay=0.1, max_delay=2.0) on an idempotent GET is the right shape, as are timing and metrics decorators where the scope genuinely is the whole call. Reach for contextlib.ExitStack when the number of scopes is dynamic rather than fixed.

Curated: · Written: · Reviewed:

Difficulty: Hard