Iterators, Generators, O(1) Streaming Pipelines, Decorators & Context Managers
- ✓ An Iterable implements __iter__() returning a fresh Iterator; an Iterator implements both __iter__() (returning self) and __next__() (raising StopIteration when exhausted)—iterators are single-pass!
- ✓ A generator function (containing yield) compiles into a heap-allocated PyGenObject that suspends and resumes its execution stack frame (gi_frame) on each next() call, enabling O(1)-memory streaming pipelines.
- ✓ Always apply @functools.wraps(fn) inside custom decorators so the wrapped function preserves __name__, __doc__, __annotations__, and __wrapped__ (critical for FastAPI, pytest, and Pydantic schema extraction).
- ✓ Use contextlib.ExitStack (or AsyncExitStack) when acquiring a dynamic, runtime-determined number of context managers (such as connecting to N user-configured MCP tool servers).
01. The Iterator Protocol & Generator Stack-Frame State Machines
When CPython compiles a function containing the yield keyword, it sets the CO_GENERATOR flag on its PyCodeObject. Calling the function does not execute its body—instead, it returns a PyGenObject holding an unstarted frame (gen.gi_frame). Each next(gen) call pushes the frame onto the VM stack, runs until the next YIELD_VALUE opcode, freezes the instruction pointer (f_lasti) and local variables in place, and returns control to the caller!
# O(1) Constant-Memory Streaming Pipeline (Processes 50 GB of JSONL logs in ~4 MiB RAM!)
def read_jsonl(lines):
return (json.loads(line) for line in lines if line.strip())
def filter_errors(events):
return (ev for ev in events if ev.get("status", 200) >= 500)
def format_alerts(events):
return (f"[{ev['service']}] HTTP {ev['status']}: {ev['msg']}" for ev in events)
# Zero items are parsed until the consumer pulls from the terminal generator!
pipeline = format_alerts(filter_errors(read_jsonl(raw_stream)))
for alert in itertools.islice(pipeline, 10):
dispatch(alert)
02.
High-Performance itertools, functools & contextlib
| Primitive | Module | Signature / Pattern | Production Use Case & Gotchas |
|---|---|---|---|
| batched(iterable, n) | itertools (3.12+) | for batch in batched(docs, 64): | Chunks arbitrary streams into fixed N-item tuples in C without materializing the full list—ideal for embedding API batches. |
| islice / chain.from_iterable | itertools | islice(gen, start, stop) | Slices and flattens nested generators lazily in O(1) auxiliary memory. |
| @lru_cache(maxsize=1024) | functools | fn.cache_info() / cache_clear() | C doubly-linked hash map memoizer. Gotcha: Never apply @lru_cache(None) to instance methods holding self unless bounded—it pins self in a global dict and leaks instances! |
| @singledispatch | functools | @serialize.register(datetime) | Clean extensible generic functions dispatching on the type of the first argument without giant isinstance() chains. |
| ExitStack / AsyncExitStack | contextlib | stack.enter_context(cm) | Programmatically manages a dynamic collection of sync or async context managers with guaranteed LIFO unwind on exceptions. |
💻 Hands-On WebAssembly Python Labs (Module 8)
Click Run & Edit Live (Wasm) on any lab below to execute and modify the code in our browser Pyodide runtime.
Lab 8.1: Lazy O(1) Generator Pipelines, yield from Delegation & Generator Frame Inspection
Inspect a live generator’s suspended stack frame (gi_frame.f_locals) and compare memory allocation of a 100,000-element list comprehension vs. a lazy generator expression.
import itertools
import sys
# 1. Memory Comparison: Eager List Comprehension vs. Lazy Generator Expression
eager_list = [x * x for x in range(50_000)]
lazy_gen = (x * x for x in range(50_000))
print("[1] Eager List vs. Lazy Generator RAM Footprint:")
print(f" Eager List (50,000 items materialized): {sys.getsizeof(eager_list):>7,} bytes")
print(f" Lazy Generator (single suspended frame): {sys.getsizeof(lazy_gen):>7,} bytes")
# 2. Sub-Generator Delegation with 'yield from' + return value capture
def stream_agent_chunk(agent_id: str, tokens: list[str]):
count = 0
for tok in tokens:
count += 1
yield f"[{agent_id}]{tok}"
return count # Captured by 'total = yield from ...'
def orchestrate_swarm():
c1 = yield from stream_agent_chunk("Planner", [" plan", " step-1", " step-2"])
c2 = yield from stream_agent_chunk("Coder", [" def", " solve():", " pass"])
yield f"[Summary] Total tokens streamed = {c1 + c2}"
print("\n[2] Streaming Sub-Generators via 'yield from':")
gen = orchestrate_swarm()
first_token = next(gen)
print(f" First yielded token: {first_token!r}")
print(f" Suspended generator frame locals: {gen.gi_frame.f_locals if gen.gi_frame else 'completed'}")
print(" Remaining stream:", list(gen))
Lab 8.2: Parameterized Retry/Telemetry Decorator (@wraps) & Dynamic contextlib.ExitStack
Build a production-grade parameterized decorator preserving function metadata and a dynamic contextlib.ExitStack managing multiple transactional resources.
from contextlib import ExitStack, contextmanager
import functools
from typing import Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
# 1. Type-Safe Parameterized Decorator Factory with @functools.wraps
def with_retry(max_attempts: int = 3):
def decorator(fn: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(fn)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
last_err: Exception | None = None
for attempt in range(1, max_attempts + 1):
try:
return fn(*args, **kwargs)
except Exception as exc:
last_err = exc
print(f" [Retry {attempt}/{max_attempts}] {fn.__name__} caught: {exc}")
assert last_err is not None
raise last_err
return wrapper
return decorator
attempts = 0
@with_retry(max_attempts=3)
def flaky_rpc_call(endpoint: str) -> str:
"""Calls upstream model gateway."""
global attempts
attempts += 1
if attempts < 3:
raise TimeoutError(f"Gateway timeout on {endpoint}")
return f"200 OK from {endpoint} on attempt #{attempts}"
print("[1] Executing @with_retry Decorated Function:")
print(" Result:", flaky_rpc_call("/v1/responses"))
print(f" Preserved Metadata: __name__={flaky_rpc_call.__name__!r}, __doc__={flaky_rpc_call.__doc__!r}")
# 2. Dynamic Resource Management with contextlib.ExitStack
@contextmanager
def mcp_session(server_name: str):
print(f" [+] Connected MCP session: {server_name}")
try:
yield f"session://{server_name}"
finally:
print(f" [-] Cleanly closed MCP session: {server_name} (LIFO unwind)")
print("\n[2] Acquiring Dynamic Pool of MCP Sessions via ExitStack:")
servers = ["github-mcp", "postgres-mcp", "filesystem-mcp"]
with ExitStack() as stack:
active_handles = [stack.enter_context(mcp_session(srv)) for srv in servers]
print(" Active handles inside with-block:", active_handles)
Frequently Asked Staff Interview Questions (Module 8)
What is the difference between an Iterable and an Iterator in Python? ▸
An Iterable (like a list, tuple, dict, or custom class with __iter__) represents a collection that can be iterated over multiple times because each iter(iterable) call returns a new Iterator cursor. An Iterator (like a generator object or zip/map result) holds mutable cursor state via __next__() and returns itself from __iter__(); once consumed, subsequent loops over the same iterator yield zero items.
What does yield from do beyond a simple for item in subgen: yield item loop? ▸
yield from subgen establishes a transparent two-way bidirectional channel between the outer caller and the inner sub-generator: it forwards .send(value) payloads, propagates .throw(exc) exceptions, handles .close() cleanup, and captures the sub-generator’s final return value via StopIteration.value.
Why is contextlib.ExitStack essential in production Python systems? ▸
A static with open(a), open(b): statement only works when the number of resources is fixed at author time. ExitStack maintains a LIFO stack of registered __exit__ callbacks at runtime (stack.enter_context(cm)), guaranteeing that if acquisition #4 fails, resources #3, #2, and #1 are unwound in reverse order.