Mental model
Python generators (yield) decouple producing arbitrary data streams cleanly from allocating complete collections in memory (O(1) streaming footprint rather than O(N) lists), while context managers (with / async with) enforce deterministic acquisition and cleanup invariants (RAII) around code blocks even when exceptions, timeouts, or early returns unwind stack frames abruptly. Combining @contextmanager, @asynccontextmanager, and ExitStack stops file-descriptor and DB-connection leaks cleanly at scale.
Learning outcomes
- Implement synchronous and async context managers cleanly via dunder methods (
__enter__/__exit__,__aenter__/__aexit__),@contextmanager, andAsyncExitStack. - Stream multi-gigabyte embeddings, JSONL logs, and RAG corpora in
O(1)RAM using lazy generator pipelines (yield/yield from). - Prevent hidden resource leaks and silent exception suppression inside
finallycleanup paths (never returning True accidentally from __exit__).
Theory
Allocating large query results with [parse(row) for row in huge_file] exhausts container memory quickly under concurrent traffic, whereas generator functions pause frame execution at yield and hand over items one at a time cleanly across upstream iterators. Meanwhile, deterministic resource boundaries require guaranteed cleanup no matter how execution exits a function:
| Abstraction | Execution Semantics | Memory Profile | Primary Hazard When Misused |
|---|---|---|---|
List Comprehension ([...] ) | Materializes 100% elements eagerly upfront | O(N) RAM heap growth | Worker OOM kills on large batch ETL exports |
Generator Function (yield) | Lazy state-machine resumption on next() | O(1) working frame RAM | Single-pass exhaustion (second loop yields 0 items); unclosed generator leaks unless wrapped in with |
@contextmanager + try...finally | Suspends once cleanly around with block | Minimal frame overhead | Omitting try...finally skips cleanup cleanly whenever body raises! |
contextlib.ExitStack / AsyncExitStack | Dynamic LIFO registration for N conditional resources | Scales cleanly for unknown resource counts | Manually holding open locks outside structured blocks causes deadlock/FD exhaustion |
Two subtle Python pitfalls catch senior engineers frequently:
- Inside custom
__exit__(self, exc_type, exc_val, exc_tb), returning any truthy value (return True) silently swallows unhandled exceptions raised inside thewithbody cleanly—always returnFalseorNoneunless explicitly handling an expected sentinel! - With
@contextlib.asynccontextmanager, never open multipleasyncstreams across ad-hoc loops withoutAsyncExitStack, because an exception mid-setup orphans earlier connections unless registered in cleanup callbacks.
pythonimport timefrom contextlib import AsyncExitStack, asynccontextmanager, contextmanagerfrom typing import AsyncIterator, Iterator@contextmanagerdef leased_lock_timer(label: str) -> Iterator[dict[str, float]]:"""Deterministic sync resource timer ensuring cleanup runs even cleanly on exceptions."""metrics = {"start": time.perf_counter(), "elapsed_ms": 0.0}try:yield metricsfinally:# Runs strictly cleanly on normal completion OR exception unwindmetrics["elapsed_ms"] = (time.perf_counter() - metrics["start"]) * 1000.0def stream_jsonl_batches(lines: Iterator[str], batch_size: int = 128) -> Iterator[list[str]]:"""Yield fixed-size chunks in O(batch_size) memory rather than loading full files."""batch: list[str] = []for raw in lines:stripped = raw.strip()if not stripped:continuebatch.append(stripped)if len(batch) >= batch_size:yield batchbatch = []if batch:yield batch@asynccontextmanagerasync def scoped_connection_bundle(pool, keys: list[str]) -> AsyncIterator[list[object]]:"""Use AsyncExitStack cleanly when dynamic resource count varies at runtime."""async with AsyncExitStack() as stack:handles = [await stack.enter_async_context(pool.acquire(k)) for k in keys]yield handles
Trade-offs
Lazy generators (yield) maximize streaming efficiency over unbounded datasets and Compose pipeline stages smoothly with zero intermediate array allocations, sacrificing random index lookup (gen[5]), len() queries, and repeatable multi-pass iteration cleanly unless converted selectively (list(...) only on small filtered slices). Explicit with and ExitStack resource scoping adds clear indentation structure while guaranteeing deterministic FD/lock teardown compared to unpredictable garbage-collection __del__ finalizers that delay socket reclamation under cycles cleanly.
Failure modes and misconceptions
- Forgetting
try...finallyInside@contextmanager: Writing cleanup lines directly afteryieldwithout wrappingyieldintry...finallyleaks DB cursors cleanly whenever the caller raisesValueErrorinside thewithbody. - Accidental Exception Suppression in
__exit__: Writing a helper returning truthy objects suppresses real crashes silently cleanly. - Re-Iterating an Exhausted Generator: Passing the exact same generator object into two consecutive validation loops produces empty results cleanly on pass two without throwing errors (
materializing small metadata lists when re-used avoids subtle zero-count bugs). - Async Generator Closing Leaks Under Cancellation: Yielding across an async generator aborted prematurely outside
contextlib.aclosing(...)defers cleanup cleanly until non-deterministic GC sweeps.
Decision scenario
An embeddings ingestion worker currently loads 2.5 GB JSONL exports completely into Python lists before batching, occasionally timing out and leaking Postgres DB locks whenever JSON parse errors strike mid-file cleanly. Refactor cleanly using O(1) yield batching generators, @contextmanager transaction timing (try...finally), and contextlib.closing/AsyncExitStack resource guards cleanly.