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.
- 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:
# 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
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:
- Evaluate
exprto obtain the context manager objectmgr. - Call
mgr.__enter__(), binding its return value totarget(ifas targetis present). - Execute the indented body of the
withblock. - Always call
mgr.__exit__(exc_type, exc_val, exc_tb)upon leaving—whether by reaching the end, hittingreturn/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 returnsFalseorNone(the default), Python re-raises the original exception after cleanup finishes.
- Normal exit: Python passes
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):
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
yieldruns inside__enter__. - The yielded value is bound to
as ...(use bareyieldif callers don't need a value). - Everything in
finally:afteryieldruns inside__exit__!
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)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
| Tool | Best Used When | Key Advantage |
|---|---|---|
@contextmanager | Simple setup + teardown around a block | Half the code; local variables replace self.* |
__enter__ / __exit__ class | Rich 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/locks | Safely opens and closes an unknown number of resources |
Try It Yourself in the Playground
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
Inside a @contextmanager function, why should yield be wrapped inside try: ... finally:?
In a class-based context manager, what happens if __exit__ returns False (or None) when an exception happened inside the with block?