๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Context Managers and Resource Safety in Python

Python InterviewResource Managementโญ Premium
Python Interview ยท Difficulty: Medium

The with statement is a contract about cleanup

A context manager is an object that defines what happens before and after a block of code: setup in __enter__, guaranteed teardown in __exit__. The with statement calls them even when the block raises, which is exactly why Python developers open files, acquire locks, start timers, and enter database transactions with it rather than writing manual try/finally every time. In interviews, context manager questions reveal whether you think about failure paths โ€” a candidate who only describes the happy path has not operated the systems they are describing. The strongest answers pair the mechanism with the resources it protects and the exception semantics it controls.

Prerequisites

  • !try/except/finally
  • !Generators and the yield keyword

What You'll Learn

  • 1Implement class-based and function-based context managers with correct exception semantics
  • 2Use contextlib tools: closing, suppress, redirect_stdout, ExitStack, asynccontextmanager
  • 3Compose nested and dynamic context managers safely
  • 4Recognize when suppression, chaining, or re-raising is the right __exit__ behavior

Class-based managers: enter and exit

The protocol is small. __enter__ runs on entry and its return value becomes the as target. __exit__(exc_type, exc_val, exc_tb) runs on exit โ€” with all three arguments None when the block completed normally, and with the exception details when it raised. Returning a truthy value from __exit__ swallows the exception; returning False or None lets it propagate. Almost every manager should return a falsey value: swallowing exceptions silently is a debugging nightmare, and the rare managers that do suppress โ€” contextlib.suppress being the canonical example โ€” make the suppression explicit at the call site.

A timing manager that reports elapsed time on both success and failure is the standard whiteboard demo, and adding the exception branch shows maturity. A temporary-directory manager that creates a path in __enter__ and removes the tree in __exit__ demonstrates real cleanup. A thread-lock manager that acquires in __enter__ and releases in __exit__ connects context managers to the concurrency topic โ€” mention that threading.Lock itself supports the protocol, which is why with lock: works. Reentrancy is the subtlety to flag: acquiring the same non-reentrant lock twice inside one with stack deadlocks, so nested code paths should either share one acquisition or use RLock.

python
import shutil
import tempfile
import time
from pathlib import Path


class Timer:
    """Reports elapsed time whether the block succeeded or failed."""

    def __init__(self, label="block"):
        self.label = label
        self.elapsed = None

    def __enter__(self):
        self._start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.elapsed = time.perf_counter() - self._start
        if exc_type is None:
            print(f"{self.label} ok in {self.elapsed:.4f}s")
        else:
            print(f"{self.label} failed in {self.elapsed:.4f}s: {exc_val}")
        return False  # never swallow the exception


class TempDir:
    """Creates a directory on entry, removes the tree on exit."""

    def __enter__(self):
        self.path = Path(tempfile.mkdtemp(prefix="itw_"))
        return self.path

    def __exit__(self, exc_type, exc_val, exc_tb):
        shutil.rmtree(self.path, ignore_errors=True)
        return False


with Timer("report"):
    data = [i * i for i in range(100000)]

Function-based managers with @contextmanager

contextlib.contextmanager turns a generator into a context manager: run setup, yield the target value, then run cleanup in a finally block after the yield. This style is shorter than a class and reads top-to-bottom, which interviewers often prefer. The discipline it demands is wrapping everything from the yield onward in try/finally โ€” forgetting that re-raises nothing and leaks the resource precisely when the body fails. Code before the yield runs on entry; code after runs on exit regardless of exceptions unless you catch and re-raise.

Two function-based managers repay memorization. A chdir manager that records the current working directory, changes into a target, and restores the old path in finally. A redirect_stdout manager that swaps sys.stdout for a StringIO so a library's prints can be captured in tests โ€” knowing that the standard library ships contextlib.redirect_stdout and redirect_stderr is a nice credibility signal. Then mention closing(), which adapts any object with a close() method into a context manager, and suppress(*exceptions), which makes exception-swallowing explicit and narrow.

python
import os
from contextlib import contextmanager, suppress


@contextmanager
def chdir(path):
    """Temporarily change the working directory."""
    previous = os.getcwd()
    os.chdir(path)
    try:
        yield path
    finally:
        os.chdir(previous)


@contextmanager
def suppress_errors(*types):
    """Swallow only the listed exception types."""
    try:
        yield
    except types as exc:
        print(f"suppressed {type(exc).__name__}: {exc}")


with chdir("/tmp"):
    assert os.getcwd() == "/tmp"
with suppress_errors(FileNotFoundError):
    os.remove("never-existed.txt")

ExitStack: managing an unknown number of contexts

Sometimes the set of resources is only known at runtime โ€” opening a list of files whose length comes from configuration, or entering a variable number of database transactions. Nested with statements do not scale to dynamic counts, and ExitStack is the answer. Push contexts onto the stack with enter_context or use the stack itself as a context manager; on exit, everything is unwound in reverse order of entry, each receiving its own exception arguments. ExitStack also cleanly composes with async context managers in AsyncExitStack, a detail that earns bonus points in senior interviews.

Beyond files, ExitStack is the implementation trick behind context managers that manage other context managers: a managed_resources helper that opens connections, acquires locks, and starts transactions, then releases them all even when one acquisition halfway through fails. The interview question "what if acquiring the third resource fails after the first two succeeded?" is exactly the scenario ExitStack solves, and walking through it impresses.

Async context managers

The async world mirrors the sync protocol with __aenter__ and __aexit__, plus @asynccontextmanager for function-style managers. Async database connections, HTTP sessions, and semaphore guards all use it. The rule of thumb: if the setup or teardown awaits โ€” establishing a network connection, draining a pool โ€” the manager must be async, because a sync __enter__ would block the event loop. Pair this with the earlier lesson that async with cannot be mixed into plain with stacks without an AsyncExitStack, and you have the complete picture.

Real-world managers beyond files

Production Python uses context managers for far more than open(). Locks and semaphores guard shared state. Transaction managers commit on success and roll back on failure. Change-directory and environment-variable managers keep tests hermetic. Circuit breakers and rate limiters wrap outbound calls so failures trip a shared state machine. Metric-recording managers time a block and emit a histogram sample in the finally branch. When an interviewer asks you to "make this function production-ready," wrapping its I/O in a context manager is often the first concrete improvement you can propose โ€” and you can sketch it live in under a minute.

There is also a compositional trick worth naming: a manager that itself opens several resources can hold them on an ExitStack created in __enter__ and close the stack in __exit__, giving callers a single with for a whole session. That pattern appears in test fixtures and connection brokers, and describing it shows you can build managers out of managers rather than hand-rolling nested try/finally ladders in every call site.

Manager styleBest forException handlingBoilerplate
Class with enter/exitStateful managers, reusable typesFull control in exitMore lines
@contextmanager functionSimple setup/teardown pairstry/finally after yieldFew lines
contextlib.closingObjects with close() but no protocolDelegates to closeOne line
contextlib.suppressExplicit, narrow suppressionSwallows listed types onlyOne line
ExitStackDynamic or counted resourcesUnwinds all in reverseModerate
Async variantsAnything that awaitsSame rules, async awareSame shapes

Common Mistakes

Forgetting try/finally around the yield in @contextmanager

Fix: Everything after yield belongs in finally so cleanup runs on exceptions too

Returning True from __exit__ to be helpful

Fix: Only suppress exceptions deliberately and narrowly; otherwise return False

Nesting with-statements for a runtime-determined list of resources

Fix: Use ExitStack and enter_context for each resource

Using a sync context manager for async setup like network I/O

Fix: Implement __aenter__/__aexit__ or @asynccontextmanager so the loop is not blocked

Best Practices

  • Wrap every resource with a context manager before writing business logic
  • Keep __exit__ silent about success and loud about failure โ€” log, then re-raise
  • Put cleanup in finally after yield when using @contextmanager
  • Mention ExitStack whenever resource counts are dynamic; it shows operational thinking

Interview Questions

Q1: How do __enter__/__exit__ differ from the @contextmanager decorator?

The class protocol gives you explicit objects and full lifecycle control; @contextmanager builds the same protocol from a generator where code before yield runs on entry and code after yield (in finally) runs on exit.

Q2: How do you handle exceptions in context managers?

__exit__ receives exc_type, exc_val, and exc_tb; log or clean up, then return a falsey value to propagate. Function-based managers must wrap post-yield code in try/finally.

Q3: What is ExitStack for?

Managing a dynamic number of context managers: each enter_context call pushes another, and the stack unwinds them in reverse order on exit, even if a later acquisition fails.

Q4: When would you use async context managers?

When setup or teardown awaits โ€” network connections, database pools, semaphores in asyncio code. Using a sync manager would block the event loop during the awaited phase.

Q5: Design a transaction manager in thirty seconds.

A @contextmanager that begins a transaction, yields the connection, commits in the normal path, and rolls back in except before re-raising; close the connection in finally.

Key Takeaways

  • __enter__ sets up; __exit__ always runs and decides whether exceptions propagate
  • @contextmanager turns a generator into a manager โ€” protect the post-yield code with finally
  • ExitStack handles dynamic resource counts with reverse-order unwinding
  • Async managers exist for awaited setup and teardown; do not block the loop
  • Context managers are the idiomatic answer whenever a resource needs a guaranteed cleanup path
๐Ÿ”’

Premium Content

Context Managers and Resource Safety in Python

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-14

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement