Generators
A generator produces values one at a time, on demand, instead of building the whole sequence up front. Any function containing yield becomes a generator function, and calling it returns a paused object that computes the next value only when asked.
Detailed Explanation
You have a 40 GB access log and you want the average response time for requests to /checkout. The obvious code reads the file into a list, filters it, and averages it. That code will not run, because the list does not fit in memory. Yet the computation itself needs only one line at a time.
That gap — between "the data set is huge" and "the working set is tiny" — is what generators close. A generator is a recipe for a sequence rather than the sequence itself. It holds one value at a time plus enough state to compute the next one.
Mechanically, a function that contains yield anywhere in its body is no longer a normal function. Calling it runs none of the body. It returns a generator object, paused before the first line. Each time something asks for the next value, the body runs until it reaches a yield, hands that value back, and freezes again with its local variables intact. When the body ends, the generator raises StopIteration and is finished. The keyword mechanics, including yield from and send, are covered in the yield entry.
Before generators, Python programmers wrote callback-driven loops or hand-rolled iterator classes: a class with __iter__, __next__, and a pile of attributes tracking "where was I". A generator expresses the same thing as straight-line code, and the interpreter saves the position for you. That is the real win — you write the loop as if you were building a list, and you get lazy behaviour for free.
Three practical consequences follow.
Memory is flat rather than proportional to the data. A list of a million squares costs about 8 MB; the equivalent generator costs about a hundred bytes regardless of length. This also means a generator can be infinite. itertools.count() never ends, and that is fine as long as a consumer stops pulling.
Work is deferred and possibly skipped. If the caller breaks out of the loop after ten items, the eleventh is never computed. Building a list computes everything, then throws most of it away. For expensive per-item work — a regex, a JSON parse, an HTTP call — that is the whole cost difference.
Generators compose into pipelines. Each stage consumes the previous stage lazily, so a four-stage pipeline over a 40 GB file still holds one record in memory. itertools exists to supply the common stages: islice, chain, groupby, takewhile.
The costs are real. A generator is single-pass: once consumed it is empty, and iterating it again gives nothing rather than raising an error, which makes for confusing bugs. You cannot take len() of one, index into it, or iterate it twice without regenerating. Per-item overhead is slightly higher than a list comprehension because each value involves resuming a frame, so for small collections you consume more than once, a list is both faster and simpler.
A generator expression is the compact form: (line for line in log) with parentheses instead of the square brackets of a list comprehension. Use it when the pipeline stage is a single expression; write a generator function when it needs setup, branching, or a docstring.
Code Examples
import sys
# Eager: builds every value, then you use them.
squares_list = [n * n for n in range(1_000_000)]
# Lazy: a generator expression. Nothing has been computed yet.
squares_gen = (n * n for n in range(1_000_000))
print(sys.getsizeof(squares_list)) # 8448728 -> about 8 MB of pointers
print(sys.getsizeof(squares_gen)) # 112 -> the recipe, not the data
print(sum(squares_gen)) # 333332833333500000 <- computed one at a time
# Single-pass: the generator is now exhausted, and stays silent about it.
print(sum(squares_gen)) # 0 <- NOT an error, just nothing left
print(sum(squares_list)) # 333332833333500000 <- a list can be reusedfrom pathlib import Path
Path("access.log").write_text(
"200 /home 31\n500 /checkout 812\n200 /checkout 120\n200 /home 44\n"
)
def read_lines(path):
"""Stage 1: yield one raw line at a time; the file closes when we finish."""
with open(path, encoding="utf-8") as handle:
for line in handle:
yield line.rstrip("\n")
def parse(lines):
"""Stage 2: turn each line into a tuple. Still one record in memory."""
for line in lines:
status, path_part, millis = line.split()
yield int(status), path_part, int(millis)
def only_checkout(records):
"""Stage 3: filter. Records that fail the test are never passed on."""
for status, path_part, millis in records:
if path_part == "/checkout":
yield status, millis
# Nothing has run yet: these three lines only wire the pipeline together.
pipeline = only_checkout(parse(read_lines("access.log")))
# Pulling the first value drives every stage exactly one step.
print(next(pipeline)) # (500, 812)
print(list(pipeline)) # [(200, 120)] <- the rest, drainedimport itertools
def fibonacci():
"""An infinite generator. Legal, because the consumer decides when to stop."""
previous, current = 0, 1
while True: # no exit condition: that is the point
yield previous
previous, current = current, previous + current
# islice stops pulling after 10 values, so only 10 are ever computed.
print(list(itertools.islice(fibonacci(), 10)))
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# takewhile stops at the first value that fails the test.
print(list(itertools.takewhile(lambda n: n < 100, fibonacci())))
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
def instrumented():
for value in range(5):
print(f" computing {value}")
yield value
# Breaking early means the remaining values are never produced.
for value in instrumented():
if value == 2:
break
# computing 0
# computing 1
# computing 2 <- 3 and 4 never happenCommon Gotchas
A generator is single-pass and fails quietly
after you iterate it once it is empty. A second `for` loop over the same generator object runs zero times and raises nothing, so code that iterates twice silently returns empty results. If you need two passes, materialise with `list(...)` or call the generator function again.
Calling the function runs none of the body
validation at the top of a generator function does not execute until the first value is pulled. A `ValueError` you expected at call time surfaces much later, often inside an unrelated loop. Validate in a plain wrapper function that returns the generator.
No `len()`, no indexing, no slicing
`len(gen)` raises `TypeError` and `gen[0]` raises `TypeError`. Use `itertools.islice` for slicing, and `sum(1 for _ in gen)` if you truly need a count — which consumes the generator.
Laziness and resource lifetime interact
a generator that opens a file in a `with` block keeps that file open until it is exhausted or garbage collected. Abandon it halfway and the descriptor stays open until CPython's reference counting cleans it up, which is prompt in CPython but not guaranteed by the language.