Sub topic 11
Avoiding large allocations with generators
This chapter assumes you know the following:
- How names bind to objects.
- That a list holds references to objects, and
sys.getsizeofis shallow. - Basic
forloops and function definitions.
You do not need prior experience with yield. The chapter covers it.
The problem: building everything before using anything
A list comprehension builds every element before the next line of code runs. If you only need to loop over the results once, that full list is wasted memory. For a million integers, the list stores a million pointers and a million int objects. All of them stay alive until the list is freed.
A generator avoids this. It produces one value at a time and keeps only its own small state between values.
import sys
squares_list = [n * n for n in range(1_000_000)]
squares_gen = (n * n for n in range(1_000_000))
print(sys.getsizeof(squares_list) > sys.getsizeof(squares_gen)) # True
print(sum(squares_gen))The list object alone is several megabytes. The generator object is a couple hundred bytes, whatever the range size. sum asks the generator for one value, adds it, and drops it. By the time the next value is computed, the previous int has usually been freed by reference counting.
How a generator works
A generator is an object that wraps a paused function frame. The frame holds local variables and the position of the next instruction. Each call to next() resumes the frame until it reaches a yield. Then it pauses again and hands back the yielded value.
There are two ways to write one:
- A generator expression,
(expr for x in iterable), is the compact form. - A generator function is any function that contains
yield. Calling it runs none of its body. It returns a generator object.
Measuring the difference with tracemalloc
sys.getsizeof only measures the container, so it understates what the list costs. To see the real effect, measure the peak memory traced during each computation. The tracemalloc module is covered in detail in a later chapter. Here you only need get_traced_memory(), which returns the current and peak traced sizes in bytes.
import tracemalloc
def peak_of(func):
tracemalloc.start()
func()
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak
def total_list():
return sum([n * n for n in range(1_000_000)])
def total_gen():
return sum(n * n for n in range(1_000_000))
print(f"list: {peak_of(total_list) / 1_000_000:.1f} MB")
print(f"gen: {peak_of(total_gen) / 1_000_000:.3f} MB")The exact numbers depend on your Python version and platform. Expect the list version to peak in the tens of megabytes and the generator version to stay in the kilobytes. Both produce the same sum.
Pipelines: processing data larger than memory
Generators compose. Each stage takes an iterable and yields transformed items, so a whole pipeline holds roughly one item at a time. This is how you process a file larger than RAM.
import os
import tempfile
def read_lines(path):
with open(path) as f:
for line in f:
yield line.rstrip("\n")
def errors_only(lines):
for line in lines:
if line.startswith("ERROR"):
yield line
def count(iterable):
return sum(1 for _ in iterable)
with tempfile.NamedTemporaryFile("w", suffix=".log", delete=False) as tmp:
for i in range(10_000):
level = "ERROR" if i % 100 == 0 else "INFO"
tmp.write(f"{level} event {i}\n")
try:
print(count(errors_only(read_lines(tmp.name)))) # 100
finally:
os.remove(tmp.name)Nothing reads the file until count starts pulling. File objects are themselves lazy iterators over lines. Calling f.readlines() instead would load the entire file into a list.
Processing in chunks
Sometimes you need batches, for example to insert 1,000 rows at a time. A generator can yield fixed-size lists. Memory is then bounded by the chunk size instead of the input size.
from itertools import islice
def chunks(iterable, size):
it = iter(iterable)
while chunk := list(islice(it, size)):
yield chunk
for batch in chunks(range(10), 4):
print(batch)
# [0, 1, 2, 3]
# [4, 5, 6, 7]
# [8, 9]The walrus operator (:=) needs Python 3.8 or later. Python 3.12 added itertools.batched, which does the same job with tuples.
Edge cases and common errors
A generator can be consumed only once
After a generator is exhausted, it stays empty. Looping over it again silently produces nothing.
gen = (n for n in range(3))
print(list(gen)) # [0, 1, 2]
print(list(gen)) # []If you need several passes, either recreate the generator by calling the function again, or accept the cost of storing the results in a list. Do not call itertools.tee as a shortcut. It buffers every item that one copy has consumed and the other has not, so it can use as much memory as the list you were avoiding.
Functions that materialize their input
Some operations need all the data at once and defeat the savings:
list(gen),tuple(gen),set(gen), andsorted(gen)build a full container.len()does not work on generators at all. Count withsum(1 for _ in gen).- Slicing with
gen[:10]fails. Useitertools.islice(gen, 10). min,max,sum,any,all, and"".join(...)consume the iterator item by item, so they are safe. One caveat:str.joinconverts its argument to a list internally, so a generator gives no memory benefit there.
Late evaluation of names
Only the outermost iterable of a generator expression is evaluated immediately. Everything else runs when values are pulled. If a name changes in between, the generator sees the new value.
x = 10
g = (x * n for n in range(3))
x = 100
print(list(g)) # [0, 100, 200], not [0, 10, 20]Generators keep their frame alive
A paused generator holds references to its local variables. If the frame holds a large object, that object stays alive for as long as the generator does. Reference counting cannot free it, because the generator still points to it.
def first_item(big_data):
yield big_data[0] # big_data stays referenced while the generator exists
gen = first_item(list(range(1_000_000)))
next(gen)
# The million-element list is still alive here, held by the generator's frame.
del gen # now the frame is released and the list is freedThe same applies to resources. A generator that opens a file inside a with block keeps the file open while it is paused. If you stop iterating early, close the generator explicitly with gen.close(). That raises GeneratorExit inside it, so the with block exits and the file closes. CPython also does this when the generator is freed, but you should not rely on timing in long-lived references or on other interpreters.
Laziness delays errors
Because no body code runs at call time, an exception in a generator function appears at the first next(), not where you called the function. A bad argument therefore fails far from the line that caused it. Validate arguments in a regular function that then returns the generator:
def read_numbers(path):
if not path:
raise ValueError("path is required") # raised at call time
return _read_numbers(path)
def _read_numbers(path):
with open(path) as f:
for line in f:
yield int(line)When a list is still the better choice
Use a generator when you iterate once, the data is large or unbounded, or early exit is likely. Use a list when you:
- iterate several times,
- need
len, indexing, or slicing, - need random access or sorting,
- have a small dataset, where a list is faster and clearer.
Generators also add per-item overhead from resuming the frame, so a list can be faster for small, reused data. Measure before assuming.
Summary of the memory model
| Approach | Memory held | Reusable | Supports `len` and indexing |
|---|---|---|---|
| List comprehension | All items at once | Yes | Yes |
| Generator expression | One item plus the paused frame | No, single pass | No |
| Generator function | One item plus the paused frame and its locals | No, single pass | No |
Exercise
The function below is meant to count lines that contain "ERROR" in a very large file, but it uses a lot of memory. Name the line that causes it, and rewrite the function so memory use does not grow with file size. def count_errors(path): with open(path) as f: lines = f.readlines() return len([line for line in lines if "ERROR" in line])
Show answer
f.readlines() loads every line into one list, and the list comprehension then builds a second list of matches. Iterate over the file directly and use a generator expression:
def count_errors(path):
with open(path) as f:
return sum(1 for line in f if "ERROR" in line)
The file object yields one line at a time, and sum consumes the generator without storing the matches, so memory stays roughly constant.
Exercise
What does the second print statement output, and why? gen = (n * 2 for n in range(3)) print(sum(gen)) print(sum(gen))
Show answer
The first print outputs 6. The second prints 0. The generator is exhausted after the first sum, so it yields nothing the second time and sum of an empty iterable is 0. No error is raised. To use the values twice, store them in a list or build a new generator.