Library

Volume 3 · Python Deep Dive

Notebook
Sign in

Section 11

Iterators, Generators & Context Managers (lazy evaluation, generator pipelines, itertools recipes, contextlib)

875 words · about 4 min

11.1 Iteration Protocol

iterable = [1, 2, 3]
iterator = iter(iterable)     # calls __iter__
next(iterator)                 # calls __next__ → 1, 2, 3, then StopIteration

An iterable implements __iter__ (can produce a fresh iterator each time — supports repeated iteration). An iterator implements both __iter__ (returning itself) and __next__ (stateful, single-pass, exhaustible).

11.2 Generators — Lazy Evaluation

def count_up(n):
    i = 1
    while i <= n:
        yield i     # suspends here, resumes on next()
        i += 1

# List comprehension: all values in memory (~8MB for 1M items)
squares_list = [x**2 for x in range(1_000_000)]
# Generator expression: ~120 bytes regardless of size — computed lazily on demand
squares_gen = (x**2 for x in range(1_000_000))

send() enables bidirectional communication (coroutine-style); throw()/close() inject exceptions or terminate a generator cleanly, typically handled with try/except GeneratorExit.

11.3 yield from — Proper Delegation

def flatten(nested):
    for item in nested:
        if isinstance(item, (list, tuple)):
            yield from flatten(item)   # Recursively delegates
        else:
            yield item

yield from isn’t just sugar for a manual for loop — it correctly forwards send() values, throw() exceptions, close() calls, and captures the sub-generator’s return value, all of which a hand-rolled for item in gen: yield item loop does not.

11.4 Generator Pipelines

def read_lines(fp):
    with open(fp) as f:
        for line in f: yield line.rstrip('\n')

def filter_comments(lines):
    for line in lines:
        if not line.startswith('#'): yield line

def parse_csv(lines):
    for line in lines: yield line.split(',')

# Lazily composed — processes ONE record at a time, O(1) memory regardless of file size
pipeline = parse_csv(filter_comments(read_lines("data.csv")))
for record in pipeline:
    process(record)

11.5 itertools Essentials

from itertools import (
    count, cycle, product, permutations, combinations,
    chain, islice, groupby, accumulate, takewhile, dropwhile, pairwise, tee
)

list(combinations("ABCD", 2))         # all size-2 subsets
list(accumulate([1,2,3,4,5]))          # [1, 3, 6, 10, 15] — running totals
list(pairwise([1,2,3,4]))              # [(1,2),(2,3),(3,4)] — 3.10+

for key, group in groupby([("A",1),("A",2),("B",3)], key=lambda x: x[0]):
    print(key, list(group))            # Groups only CONSECUTIVE equal keys

11.6 Context Managers

class FileManager:
    def __enter__(self):
        self.file = open(self.filename, self.mode)
        return self.file
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.file.close()
        return exc_type is ValueError   # True suppresses; False/None propagates

from contextlib import contextmanager, suppress, ExitStack

@contextmanager
def timer(label=""):
    start = time.perf_counter()
    try:
        yield                           # 'with' block body executes here
    finally:
        print(f"{label} took {time.perf_counter()-start:.4f}s")

with suppress(FileNotFoundError):
    os.remove("nonexistent.txt")

with ExitStack() as stack:
    files = [stack.enter_context(open(f)) for f in filenames]  # all closed on exit

class AsyncDatabase:
    async def __aenter__(self):
        self.conn = await create_async_connection(); return self.conn
    async def __aexit__(self, *args):
        await self.conn.close()

Interview Q&A — Section 11

Q1: What’s the difference between an iterable and an iterator?

A: An iterable produces a fresh iterator each time iter() is called on it — a list can support multiple independent iterations. An iterator maintains its own position and is exhausted after one pass (__next__ raises StopIteration once done); it returns itself from __iter__. Practical rule: if you need to iterate a collection multiple times, make your class an iterable that returns a new iterator each time; if single-pass is fine, the object can be its own iterator.

Q2: How do generators save memory compared to lists, and when should you use each?

A: Generators compute values lazily, one at a time — a generator expression over a million items uses ~120 bytes versus ~8MB for the equivalent list. Use generators for large/streaming datasets, single-pass processing, or pipelines where early termination is possible. Use lists when you need random access, multiple iterations, len(), slicing, sorting, or in-place mutation.

Q3: What is yield from and how does it differ from manually looping and yielding?

A: yield from delegates fully to a sub-generator: it forwards values from next(), forwards send() values into the sub-generator, forwards throw() exceptions, properly closes the sub-generator, and captures its return value. A naive for item in gen: yield item only replicates the next() forwarding — it silently breaks send/throw/close/return semantics, which matters the moment the sub-generator is used as a coroutine rather than a pure value producer.

Q4: Implement a context manager that measures execution time, including on failure.

from contextlib import contextmanager
import time

@contextmanager
def timed_block(label="Block"):
    start = time.perf_counter()
    error = None
    try:
        yield
    except Exception as e:
        error = e
        raise
    finally:
        elapsed = time.perf_counter() - start
        status = "FAILED" if error else "OK"
        print(f"[{status}] {label}: {elapsed:.4f}s")

The finally block guarantees the timing/logging runs whether the body succeeds or raises; re-raising inside except preserves the original traceback for the caller.