Generators

A generator function returns a generator object when called; each step of iteration advances to yield, produces one value, and suspends execution until resumed from its saved state—making it ideal for on-demand data streams.

One-Sentence Definition

A generator function returns a lazy generator object when called; each iteration step advances execution to yield, emits a single value, and suspends the stack frame so the next step resumes from the saved state—ideal for on-demand data streams.

Why It Matters

  • Memory efficiency: Producing one item at a time lets you process multi-gigabyte log files line by line without loading the entire file into RAM (peak memory depends only on active frame state and buffers).
  • Concise syntax: A 4-line generator function replaces puluhan lines of boilerplate iterator classes implementing __iter__ and __next__.
  • Foundation of streaming pipelines: ETL data pipelines, token-by-token LLM streaming responses, line-by-line JSONL readers, contextlib.contextmanager, and classic coroutines all build on generators.

Practical Boundaries

Lazy evaluation does not automatically guarantee constant memory: local variables held inside the generator frame, internal caches, I/O read buffers, or a downstream list() call can still accumulate significant memory. Likewise, sys.getsizeof measures only the shallow wrapper object, not the total memory of an entire pipeline.

How It Works / Diagram

Generators were introduced in PEP 255 (Python 2.2), enhanced with two-way send() in PEP 342, and given sub-generator delegation via yield from in PEP 380: https://peps.python.org/pep-0255/ , https://peps.python.org/pep-0342/ , https://peps.python.org/pep-0380/

Calling a generator function does not execute its body immediately—it returns a generator object that advances only when next() is called:

Figure 1

Chaining generator stages into a streaming pipeline (analogous to Unix cat | grep | sort):

Figure 2

Runnable Example

# File: examples/21_generator.py
# Generators: lazy iterators written with yield that produce items on demand
import sys

def read_lines(n):
    for i in range(n):
        yield f"line {i}"            # Suspends here on each next() call

lst = [f"line {i}" for i in range(100_000)]
gen = (f"line {i}" for i in range(100_000))
print("List shallow bytes:", sys.getsizeof(lst), "| Generator object bytes:", sys.getsizeof(gen))

# Generator pipeline: stream item-by-item like a Unix pipe (e.g., streaming large text corpora)
def parse(lines):
    for line in lines:
        yield line.upper()
def keep_even(lines):
    for line in lines:
        if int(line.split()[-1]) % 2 == 0:
            yield line
pipeline = keep_even(parse(read_lines(7)))
print("Pipeline result:", list(pipeline))

# Observing suspend and resume
def demo():
    print("  -> start"); yield 1
    print("  -> resume"); yield 2
    print("  -> end")
g = demo()
print("next:", next(g)); print("next:", next(g))
print("remaining:", list(g))

# yield from delegation; two-way communication via send()
def inner(): yield "a"; yield "b"
def outer(): yield from inner(); yield "c"
print("yield from:", list(outer()))

def running_avg():
    total, count, avg = 0, 0, None
    while True:
        x = yield avg
        total, count = total + x, count + 1
        avg = total / count
ra = running_avg(); next(ra)
print("Running average via send:", [ra.send(v) for v in [10, 20, 60]])

Captured output (Python 3.15.0):

List shallow bytes: 800984 | Generator object bytes: 216
Pipeline result: ['LINE 0', 'LINE 2', 'LINE 4', 'LINE 6']
  -> start
next: 1
  -> resume
next: 2
  -> end
remaining: []
yield from: ['a', 'b', 'c']
Running average via send: [10.0, 15.0, 30.0]
  • The memory comparison measures the shallow container size of the list object versus the generator object without recursively summing referenced elements—sys.getsizeof reflects the generator frame wrapper, not every object referenced inside its state.
  • The interleaved start / resume / end lines make the suspend-and-resume lifecycle directly visible.
  • send() feeds values back into the suspended yield expression, enabling stateful stream processors like a running average calculator.

Common Pitfalls

  • A generator can only be consumed once: Like any iterator, once exhausted it yields nothing on a second pass (see k1.py.iterator).
  • Calling len() or indexing gen[0] on a generator: Generators do not support random access or length queries. Converting with list(gen) materializes every item in memory, forfeiting lazy evaluation.
  • Assuming calling a generator function runs its validation code immediately: The body does not start until the first next() call, meaning argument validation errors inside the body are also deferred until iteration starts.
  • Opening files or sockets inside a generator without cleanup guarantees: If a consumer breaks out of a loop early, cleanup code after yield may wait until garbage collection. Wrap resource lifetimes in with blocks or try/finally, and close generators explicitly when needed.
  • Using list comprehensions over massive datasets: [f(x) for x in huge] allocates the full result list upfront; switch to a generator expression (f(x) for x in huge) or pass it directly to reductions like sum(f(x) for x in huge).

Connection to AI Development

  • Token-by-token LLM streaming: Web frameworks such as FastAPI's StreamingResponse and Streamlit's st.write_stream accept generators (sync or async) to push chunks to the browser as tokens arrive. See Streamlit st.write_stream: https://docs.streamlit.io/develop/api-reference/write-magic/st.write_stream
  • Large-corpus JSONL preprocessing: Stream-reading, cleaning, tokenizing, and writing multi-gigabyte training datasets line by line without exhausting host RAM.
  • Custom PyTorch IterableDataset pipelines: The __iter__ method of an IterableDataset is commonly implemented as a generator. https://docs.pytorch.org/docs/stable/data.html#iterable-style-datasets
  • Agent execution event streams: Modern agent harnesses emit "thinking → tool_call → tool_result" events through async generators so UIs can render progress live.

Further Reading

Concept Check

If you immediately wrap a generator in list(gen), do you still keep its memory-saving advantage?

Reference answer: No—list(gen) materializes every yielded element in memory at once. Peak memory stays low only when items are consumed incrementally without accumulating the entire sequence.

Verification & Reproduction

Verified on: 2026-10-14. Example status: Passed. Run log: 21_generator.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram