3. Modern OOP, Dataclasses & Context Managers

Context Managers (with) & Custom Resource Safety

Understand how Python's with statement guarantees cleanup even when crashes happen, and build your own context managers using __enter__/__exit__ and @contextlib.contextmanager.

4 min readUpdated 2026-11-30
In This Lesson
  • Explain why with blocks guarantee cleanup even if an exception is raised inside
  • Write a class-based context manager implementing __enter__ and __exit__
  • Build concise generator-based context managers using @contextlib.contextmanager

You have already used with open("data.txt") as f: so Python closes files automatically. That with block isn't special magic reserved for files—it is an open protocol called Context Managers, and you can use it for database transactions, timers, locks, temporary directories, and test setups!

Why It Matters: Before vs After

Without with, if an exception happens—or even an early return—between acquire() and release(), your cleanup line is skipped, silently leaking open file handles or database locks:

python
# Before: fragile manual cleanup (leaks if process() raises or returns early)
conn = open_connection()
process(conn)
conn.close()

# Even try/finally forces callers to remember cleanup every single time:
conn = open_connection()
try:
    process(conn)
finally:
    conn.close()

# After: the resource owns its own guaranteed setup + teardown
with open_connection() as conn:
    process(conn)

1. Deep Mental Model: How with Executes Step by Step

Context Manager Lifecycle (with ... as ...:)

1. __enter__()

Open file / start timer / snapshot

2. with Body Runs

Normal exit OR exception raised

3. __exit__(exc_type, ...)

Guaranteed cleanup / rollback!

Whether the body succeeds or raises an exception, __exit__ (or finally:) is guaranteed to run cleanup.

When Python enters with expr as target:, it runs a strict 4-step lifecycle:

  1. Evaluate expr to obtain the context manager object mgr.
  2. Call mgr.__enter__(), binding its return value to target (if as target is present).
  3. Execute the indented body of the with block.
  4. Always call mgr.__exit__(exc_type, exc_val, exc_tb) upon leaving—whether by reaching the end, hitting return/break, or raising an exception:
    • Normal exit: Python passes (None, None, None).
    • Exception raised: Python passes (ValueError, err_instance, traceback_obj). If __exit__ returns a truthy value (True), the exception is suppressed; if it returns False or None (the default), Python re-raises the original exception after cleanup finishes.

2. Option 1: Class-Based Context Manager (__enter__ & __exit__)

Use a class when your context manager holds reusable state or methods (such as a timer, database session, or connection pool):

python
import time

class TimerBlock:
    def __init__(self, label: str):
        self.label = label
        self.elapsed_ms = 0.0

    def __enter__(self):
        self.start = time.perf_counter()
        return self  # Bound to `as t`, so callers can inspect t.elapsed_ms!

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.elapsed_ms = (time.perf_counter() - self.start) * 1000
        status = "FAILED" if exc_type else "OK"
        print(f"[{self.label}] {status} in {self.elapsed_ms:.2f} ms")
        return False  # Propagate any exception normally!

with TimerBlock("compute") as t:
    total = sum(range(50_000))

3. Option 2: @contextlib.contextmanager (Concise Generator Way)

For 90% of custom context managers, writing a generator with @contextmanager is much shorter:

  • Everything before yield runs inside __enter__.
  • The yielded value is bound to as ... (use bare yield if callers don't need a value).
  • Everything in finally: after yield runs inside __exit__!
python
from contextlib import contextmanager

@contextmanager
def temporary_setting(config: dict, key: str, temp_value):
    had_key = key in config
    old_value = config.get(key)
    config[key] = temp_value
    try:
        yield config
    finally:
        if had_key:
            config[key] = old_value
        else:
            config.pop(key, None)
Always Wrap yield in try / finally

Inside @contextmanager, if code inside the caller's with block raises an exception, Python injects and re-raises that exact exception at the yield line! Without try: yield ... finally: cleanup(), your cleanup code after yield is skipped.

Decision Table: Class vs @contextmanager vs contextlib Helpers

ToolBest Used WhenKey Advantage
@contextmanagerSimple setup + teardown around a blockHalf the code; local variables replace self.*
__enter__ / __exit__ classRich stateful object (t.elapsed_ms, conn.query())Explicit methods, attributes, and re-usable instances
contextlib.suppress(Exc)Intentionally ignoring expected errors (e.g., FileNotFoundError)Replaces noisy try: ... except FileNotFoundError: pass
contextlib.ExitStack()Managing a dynamic list of N files/locksSafely opens and closes an unknown number of resources

Try It Yourself in the Playground

Python 3Try It Live: Context Managers & @contextmanager
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Write a @contextmanager named section(title: str) that prints === {title} === on entry and --- end {title} --- in a finally: block on exit.

Quick Checkpoints

Check Your Understanding

Inside a @contextmanager function, why should yield be wrapped inside try: ... finally:?

Check Your Understanding

In a class-based context manager, what happens if __exit__ returns False (or None) when an exception happened inside the with block?