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.

Read
47 min
Practice MCQs
25
Interview Q&A
25
Edition
v2
Editorial status
Reviewed

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

Curated: · Written: · Reviewed:

25 questions

MCQ-1`plugins.py` sets `registry = {}` at module level and defines `register(fn)`, which does `registry[fn.__name__] = fn` and returns `fn`. A test does `import plugins` and asserts `plugins.registry == {}` before dispatching any event; the assertion fails with `{'ping': <function ping at 0x...>}`. The only thing that ever happened to `ping` is that it is decorated with `@register`. Which timing of the decoration call explains the failure?
MCQ-10A module applies a plain function as a class decorator: `@tag class Order: ...`. Which statement correctly describes what `tag` receives and what the name `Order` refers to once the module has finished executing?
MCQ-3Two ways of building a decorator, applied to four functions: ```python def make_tagger(name): def tag(fn): fn.tag = name return fn return tag direct = [] for label in ["a", "b"]: def tag_direct(fn): fn.tag = label return fn direct.append(tag_direct) factory = [make_tagger(n) for n in ["a", "b"]] def f1(): pass def f2(): pass def f3(): pass def f4(): pass f1 = direct[0](f1) f2 = factory[0](f2) f3 = direct[1](f3) f4 = factory[1](f4) print(f1.tag, f2.tag, f3.tag, f4.tag) ``` What does the final line print?
MCQ-6How many callable layers are normally involved in `@retry(limit=3)`?
MCQ-2For `@authorize` above `@cache`, which wrapper receives the original function first?
MCQ-5A service wraps its handlers with a retry decorator: ```python def retry(fn): def wrapper(*args, **kwargs): for attempt in range(3): try: return fn(*args) except TransientError: if attempt == 2: raise return wrapper @retry def fetch(url, *, timeout): return http.get(url, timeout=timeout) ``` `fetch("https://api/orders", timeout=0.5)` raises `TypeError: fetch() missing 1 required keyword-only argument: 'timeout'`. Which statement identifies the cause?
MCQ-4A generic decorator is applied to dozens of request handlers whose parameter lists differ and change often. The handlers still run correctly, but the DI container, which resolves arguments by calling `inspect.signature` on the handler, now sees `(*args, **kwargs)` and injects nothing. Which change makes the container see each handler's real parameters?
MCQ-7A `@timed` decorator is a plain `def` that records `time.perf_counter()`, calls the wrapped function, logs the delta, and returns the result. Applied to an `async def` that awaits a 500 ms call and then raises, it logs `0.0000s` and the exception never reaches the log. What change makes the decorator report the coroutine's real duration and log its exception?
MCQ-9A decorator that returns an instance of a callable class works on module-level functions but fails on methods: ```python class Trace: def __init__(self, fn): self.fn = fn def __call__(self, *args, **kwargs): return self.fn(*args, **kwargs) class Service: @Trace def handle(self, req): return req Service().handle("x") # TypeError: handle() missing 1 required positional argument: 'req' ``` The same decorator returning a plain function binds `self` correctly. Why does the callable-instance version not?
MCQ-11A nightly importer defines `load_batch(path)`, which parses a CSV and calls `sys.exit(2)` when the header row is malformed, and applies this decorator to it (Python 3.12): ```python import time def retry(fn): def wrapper(*args, **kwargs): for attempt in range(3): try: return fn(*args, **kwargs) except BaseException: if attempt == 2: raise time.sleep(2 ** attempt) return wrapper ``` The operator runs it on a file whose header row is malformed. What does the operator observe?
MCQ-13If `__enter__` fails after acquiring one of several resources, does `with` call `__exit__`?
MCQ-12A `Transaction` context manager must commit when the `with` body completes cleanly and roll back when it raises: ```python def __exit__(self, exc_type, exc_value, tb): if exc_type is None: self.commit() else: self.rollback() return False ``` A reviewer rejects the PR, saying `__exit__` is handed the transaction object and the value bound by `as`, so `exc_type` is never `None` and the commit branch is dead code. Which statement about the arguments `__exit__` receives is correct?
MCQ-20A request handler tears down its resources with a single `ExitStack`: it enters a DB connection, then a temp file, then registers two flush callbacks. The block body exits normally. Which order does `ExitStack` invoke the four cleanups?
MCQ-14A `Transaction` context manager's `__exit__` body is `self.rollback()` followed by `return self._pending`, a list that is non-empty whenever the body wrote anything. A `ValueError` raised inside the `with` body never reaches the caller. What is the cause?
MCQ-17When is `contextlib.suppress(FileNotFoundError)` a defensible choice?
MCQ-16A module caches `mgr = session()`, where `session` is decorated with `@contextlib.contextmanager`. The first `with mgr:` block runs normally. The second `with mgr:` raises `RuntimeError: generator didn't yield` before its body executes. What causes the failure?
MCQ-15A service wraps a transaction in a context manager: ```python from contextlib import contextmanager @contextmanager def tx(conn): conn.execute("BEGIN") try: yield conn except Exception: log.warning("tx failed") return conn.execute("COMMIT") with tx(conn): conn.execute("INSERT INTO orders ...") raise ValueError("bad row") print("after with") ``` The `INSERT` succeeds, then the body raises. What does the caller observe?
MCQ-21A request handler wraps its work in an `ExitStack` and enters two context managers, `outer` first and `inner` second. `inner.__exit__` returns `True`; `outer.__exit__` returns `None`. Each appends `(name, exc_type.__name__ if exc_type else None)` to a shared list `log`. The body raises `ValueError('boom')`. ```python class Probe: def __init__(self, name, log, suppress=False): self.name, self.log, self.suppress = name, log, suppress def __enter__(self): return self def __exit__(self, et, e, tb): self.log.append((self.name, et.__name__ if et else None)) return self.suppress log = [] with ExitStack() as stack: stack.enter_context(Probe("outer", log)) stack.enter_context(Probe("inner", log, suppress=True)) raise ValueError("boom") ``` What is `log` after the block, and does the `ValueError` reach the caller?
MCQ-19A worker function takes an optional pooled connection and must not close one the caller supplied: ```python def run_task(conn=None): if conn is None: conn = pool.acquire() # pool configured with max_size=20 with nullcontext(conn) as c: c.execute(SQL) ``` Callers that pass their own connection are fine. Callers that pass nothing succeed for the first 20 tasks, then task 21 blocks forever inside `pool.acquire()`. Which change fixes this?
MCQ-18A request handler iterates an async generator that holds a DB cursor and `break`s after the first page, leaving the generator suspended. Wrapping it in `contextlib.aclosing` changes when the cursor is released. Why?
MCQ-22A request handler builds an `AsyncExitStack`, enters an async context manager for a pooled connection, then returns without awaiting `aclose()` and without wrapping the stack in `async with`. What happens to the connection?
MCQ-24A Python service guards a shared cache with a single `threading.Lock`, always acquired as `with lock:`. Under load, two worker threads hang forever and p99 latency spikes. Which statement correctly describes what `with lock:` guarantees in this service?
MCQ-8A callable-object decorator keeps two counters: `self.calls += 1` and `self.by_tenant[t] = self.by_tenant.get(t, 0) + 1`. The service is one process with 8 worker threads on CPython 3.12. A load test of 1,000,000 requests, split evenly across 4 tenants, leaves `/metrics` reporting `calls = 998,412` and the four tenant counts summing to 997,650. An engineer wraps only `self.calls += 1` in a `threading.Lock` and reruns the identical load test. What does the next scrape report?
MCQ-23A payments handler runs inside this context manager on Python 3.12: ```python class Tx: def __enter__(self): self.conn = pool.acquire() return self.conn def __exit__(self, exc_type, exc, tb): try: self.conn.commit() finally: pool.release(self.conn) return False ``` A handler that raises `ValueError` after its first `INSERT` leaves that row visible to other requests. Which change makes a failed unit of work invisible while still delivering the original `ValueError` to the caller?
MCQ-25A Python service's `handle_order` validates the request (5 ms), runs three INSERTs (12 ms), then POSTs to a notification service (200 ms). A `@transactional` decorator wraps the whole function. The connection pool holds 20 connections and traffic is 100 req/s. Under load p99 latency climbs, and one customer was emailed about an order that a later commit failure rolled back. Which change fixes both problems?