Sub topic 11
Avoiding large allocations with generators
This chapter assumes you know how to write functions and loops, and that you have read the earlier chapters on reference counting and sys.getsizeof. A generator is an object that produces values one at a time, on demand, instead of building them all up front.
The cost of building everything at once
A list comprehension computes every element and stores them all. Peak memory grows with the number of items. A generator expression uses parentheses and computes each value only when something asks for it.
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 generator object stays small no matter how many values it will produce. It holds only its paused execution state and the iterator over range. Its size does not depend on the number of results.
Generator functions
A function that contains yield returns a generator when you call it. Each yield hands one value to the caller and pauses the function until the next value is requested.
def read_errors(path):
with open(path) as f:
for line in f:
if "ERROR" in line:
yield line.rstrip("\n")
def first_words(lines):
for line in lines:
yield line.split()[0]Chaining generators forms a pipeline. Only one line is in flight at a time, so a multi-gigabyte log file needs only a few kilobytes of working memory.
Measuring the difference
sys.getsizeof is shallow, so use tracemalloc to compare real peak usage. get_traced_memory() returns a tuple of the current and peak traced bytes.
import tracemalloc
def peak_of(func):
tracemalloc.start()
func()
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak
def with_list():
return sum([n * n for n in range(1_000_000)])
def with_generator():
return sum(n * n for n in range(1_000_000))
print(peak_of(with_list) > peak_of(with_generator)) # TrueCommon errors
- Exhaustion. A generator can be consumed only once. A second loop over the same generator yields nothing and raises no error.
- Hidden materialization.
list(gen),sorted(gen), andlen(list(gen))build the whole sequence in memory and cancel the benefit. Prefersum,min,max,any,all, or a plainforloop. - No indexing or length. Generators do not support
gen[3]orlen(gen). If you need random access, you need a real sequence. - Late evaluation. Values are computed when consumed, not when the generator is created. If the underlying data changes in between, the generator sees the new data.
- Open resources. A generator that holds a file open keeps it open until it finishes or is closed. Use
withinside the generator, and callgen.close()if you stop early.
When to choose which
| Situation | Better choice |
|---|---|
| One pass over a large or unbounded stream | Generator |
| Reading the data several times | List or tuple |
| Need indexing, slicing, or `len` | List or tuple |
| Reducing with `sum`, `max`, `any` | Generator expression |
Exercise
The code below prints 14 and then 0. Explain why the second result is 0, and change the code so both lines print 14 without building a list. squares = (n * n for n in range(1, 4)) print(sum(squares)) print(sum(squares))
Show answer
A generator is exhausted after one full pass, so the second sum finds nothing left and returns 0. Wrap the expression in a function and create a fresh generator each time: def squares(): return (n * n for n in range(1, 4)), then print(sum(squares())) twice. Each call creates a new generator, and neither one stores all the values at once.