Learning Tips | Published Nov 16, 2026 | 7 min read

Python Context Managers and the with Statement

Learn how Python context managers manage setup and cleanup with with, __enter__, __exit__, and contextlib helpers.

Diagram showing Python with manager entry, block execution and exit cleanup, including normal and exception paths

Python context managers define setup and cleanup around a block of code. The with statement makes resource handling easier to read and safer when exceptions occur. This guide explains how built-in managers work, how to write one with a class or contextlib, and when exception suppression is appropriate.

What a context manager does

A context manager establishes a temporary runtime context for a block and performs exit behavior when the block ends. Files are the familiar example: opening a file acquires a resource, while leaving a with block closes it, including when the block raises an exception.

with open("notes.txt", encoding="utf-8") as file:
    contents = file.read()

# file has been closed after the block

The as target receives the value returned by the manager's __enter__() method. The object returned there can be the manager itself or a related object, such as a file handle.

How with handles cleanup

For a regular context manager, Python calls __enter__() before running the block and calls __exit__() when the block finishes, including during exception unwinding. The exit method receives exception details when an exception leaves the block. If it returns a true value, that exception is suppressed; otherwise the exception continues outward.

That makes cleanup reliable, but also means a poorly written __exit__() can accidentally hide errors. Most managers should return false or None so unexpected exceptions remain visible.

Write a class-based context manager

Implement __enter__ and __exit__ when the resource needs explicit state or multiple methods. This small example tracks a temporary timing scope:

from time import perf_counter

class Timer:
    def __enter__(self):
        self.started = perf_counter()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.elapsed = perf_counter() - self.started
        print(f"Elapsed: {self.elapsed:.3f}s")
        return False

with Timer() as timer:
    result = sum(range(100_000))

print(timer.elapsed)

Returning False makes the example's intent explicit: exceptions are not swallowed. In production, avoid printing from a general-purpose utility; expose the measured value or send it to an injected logger. If setup in __enter__() can fail after acquiring part of a resource, it must clean up that partial acquisition itself because a successful enter did not occur.

Use contextlib.contextmanager for simple cases

For a straightforward setup/cleanup pair, contextlib.contextmanager lets a generator function describe the block boundary. Code before yield is setup, the yielded value is bound by as, and code in finally performs cleanup:

from contextlib import contextmanager
from time import perf_counter

@contextmanager
def elapsed_time():
    started = perf_counter()
    try:
        yield
    finally:
        print(f"Elapsed: {perf_counter() - started:.3f}s")

with elapsed_time():
    do_work()

The try/finally ensures cleanup runs when the block exits normally or through an exception. If code after yield catches an exception, re-raise it unless suppression is specifically intended; otherwise the caller may believe the block succeeded.

Manage several resources cleanly

Multiple managers can appear in one with statement. Python enters them from left to right and exits them in reverse order, which mirrors nested resource scopes:

with open("source.txt", encoding="utf-8") as source, \
     open("copy.txt", "w", encoding="utf-8") as destination:
    for line in source:
        destination.write(line.upper())

When the number of managers is only known at runtime, contextlib.ExitStack can register them dynamically and still unwind in the correct order if a later acquisition fails.

Useful contextlib tools

  • closing(object): calls an object's close() method when the block exits, useful for compatible objects that are not themselves context managers.
  • nullcontext(value): provides a no-op manager when code conditionally has a resource to manage.
  • suppress(SomeError): suppresses only specified exceptions. Use it only when continuing is known to be correct; avoid broad Exception suppression.
  • ExitStack: composes a variable number of context managers and cleanup callbacks.

These helpers are documented in Python's standard library. Prefer a focused manager over a custom class when it expresses the needed lifecycle clearly.

Common mistakes

  1. Opening a resource before the with and forgetting to close it if setup fails.
  2. Returning true from __exit__() or suppressing broad exceptions without a clear recovery policy.
  3. Using a generator context manager as if it were reusable: a generator-based manager instance normally represents one use; call its decorated function again to create another.
  4. Putting unrelated work inside a resource scope, which keeps locks, files, or connections open longer than needed.
  5. Assuming cleanup can reverse external side effects. A context manager can release local resources, but it cannot automatically undo a remote API call or sent email.

Use with whenever an operation has a well-defined enter/exit lifecycle. Keep the scope narrow, make cleanup deterministic, and suppress exceptions only when the code has a specific safe way to continue.

Further reading

Want a structured Java learning path?

Explore Jaipur Engineers course options to connect Java fundamentals, debugging, backend development and project practice in a guided learning plan.

Explore the Java program   Ask for course guidance