FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Context Managers & Generators

RAII resource cleanup with context managers and memory-efficient yield generators.

Freshness: current•15 min read•Computer Science and Programming

Key Learning Outcomes

  • ✓Build custom context managers with try/finally
  • ✓Stream large datasets lazily with generators
Full Technical Reference Document

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.

Call __enter__ / __aenter__ setup
Suspend generator at yield resource
Run protected caller body
Unwind via try...finally on normal/error exit
Execute __exit__ / close iterator cleanly
Conceptual teaching model synthesized from:Python 3 Standard Library, Memory Management and Data ModelPython 3.12 AsyncIO Event Loop & Asynchronous I/O Specification

Learning outcomes

  • Implement synchronous and async context managers cleanly via dunder methods (__enter__/__exit__, __aenter__/__aexit__), @contextmanager, and AsyncExitStack.
  • 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 finally cleanup 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:

AbstractionExecution SemanticsMemory ProfilePrimary Hazard When Misused
List Comprehension ([...] )Materializes 100% elements eagerly upfrontO(N) RAM heap growthWorker OOM kills on large batch ETL exports
Generator Function (yield)Lazy state-machine resumption on next()O(1) working frame RAMSingle-pass exhaustion (second loop yields 0 items); unclosed generator leaks unless wrapped in with
@contextmanager + try...finallySuspends once cleanly around with blockMinimal frame overheadOmitting try...finally skips cleanup cleanly whenever body raises!
contextlib.ExitStack / AsyncExitStackDynamic LIFO registration for N conditional resourcesScales cleanly for unknown resource countsManually holding open locks outside structured blocks causes deadlock/FD exhaustion

Two subtle Python pitfalls catch senior engineers frequently:

  1. Inside custom __exit__(self, exc_type, exc_val, exc_tb), returning any truthy value (return True) silently swallows unhandled exceptions raised inside the with body cleanly—always return False or None unless explicitly handling an expected sentinel!
  2. With @contextlib.asynccontextmanager, never open multiple async streams across ad-hoc loops without AsyncExitStack, because an exception mid-setup orphans earlier connections unless registered in cleanup callbacks.
python
import time
from contextlib import AsyncExitStack, asynccontextmanager, contextmanager
from typing import AsyncIterator, Iterator
​
@contextmanager
def 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 metrics
finally:
# Runs strictly cleanly on normal completion OR exception unwind
metrics["elapsed_ms"] = (time.perf_counter() - metrics["start"]) * 1000.0
​
def 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:
continue
batch.append(stripped)
if len(batch) >= batch_size:
yield batch
batch = []
if batch:
yield batch
​
@asynccontextmanager
async 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...finally Inside @contextmanager: Writing cleanup lines directly after yield without wrapping yield in try...finally leaks DB cursors cleanly whenever the caller raises ValueError inside the with body.
  • 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.

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next