Sub topic 8
Lazy evaluation and memory savings
This chapter assumes you can write generator functions and generator expressions, and that you know how for loops use __iter__ and __next__. Here we look at what "lazy" means in practice and how to measure the memory it saves.
Eager versus lazy
An eager computation produces every result up front and stores them. A lazy computation produces one result only when the caller asks for it, then forgets it.
A list comprehension is eager. A generator expression is lazy. Both describe the same values, but they differ in when the work happens and how much memory is held.
import sys
eager = [x * x for x in range(1_000_000)]
lazy = (x * x for x in range(1_000_000))
print(sys.getsizeof(eager) > 1_000_000) # True
print(sys.getsizeof(lazy) < 1_000) # Truesys.getsizeof reports the size of the container object itself. For the list, that is an array of a million references. The generator is a small fixed-size object holding its paused frame and the range iterator. The squares do not exist yet.
Memory stays flat
The saving is not only about the container. A lazy pipeline keeps one item alive at a time, so peak memory does not grow with the input size.
def total_eager(n):
values = [x * x for x in range(n)]
return sum(values)
def total_lazy(n):
return sum(x * x for x in range(n))
print(total_eager(1000) == total_lazy(1000)) # TrueBoth functions return the same number. total_eager builds a list of n integers before sum starts. total_lazy hands sum one square at a time, and each square is discarded after it is added.
You can see the difference with tracemalloc, which tracks Python memory allocations.
import tracemalloc
def peak_kib(func, n):
tracemalloc.start()
func(n)
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return peak // 1024
def eager(n):
return sum([x * x for x in range(n)])
def lazy(n):
return sum(x * x for x in range(n))
print(peak_kib(eager, 200_000) > peak_kib(lazy, 200_000)) # TrueThe eager version's peak grows with n. The lazy version's peak stays close to constant.
Work is deferred too
Lazy evaluation also postpones computation. If you stop early, the unused work never happens.
def noisy_squares(n):
for x in range(n):
print(f"computing {x}")
yield x * x
for value in noisy_squares(5):
if value > 4:
breakThis prints computing 0 through computing 3 and then stops. The values for 4 are never computed. An eager list of five squares would have computed them all.
Functions such as any, all and next rely on this. any(x > 100 for x in data) stops at the first match.
When eager is the better choice
Laziness has costs, so do not use it everywhere.
- You need random access or length. A generator has no
len()and no indexing. - You need several passes. A generator is exhausted after one pass. Build a list if you will loop more than once.
- The data is small. For a few hundred items, a list is simpler and often a little faster.
- Errors surface late. A bug in a lazy stage appears only when something consumes it, which can be far from the code that caused it.
Exercise
A function reads a 20 GB log file and must count lines containing "ERROR". Should it build a list of matching lines first, or use a generator expression with sum? Explain, and write the counting expression.
Show answer
Use a generator expression, because it holds only one line at a time and memory stays flat, while a list of matches could grow large. For example, with an open file f: count = sum(1 for line in f if "ERROR" in line). The file object is itself a lazy iterator over lines, so the whole pipeline is lazy.