Part 10 / Topic 8 of 11
Generators
A generator function is a function with yield in it. Calling it does not run the body; it returns a generator (an iterator). Each next() runs the body until the next yield, hands out that value, and pauses there.
Think of a tea stall that makes each cup when a customer asks, instead of making 1,000 cups in the morning.
The Countdown class above, as a generator:
def countdown(start):
while start > 0:
yield start
start -= 1
print(list(countdown(3))) # [3, 2, 1]
gen = countdown(2)
print(next(gen), next(gen)) # 2 1
Lazy evaluation
Lazy evaluation means a value is made only at the moment it is needed.
def make_tokens():
for n in range(1, 4):
print(" making", n)
yield n
tokens = make_tokens() # nothing printed yet
print("first:", next(tokens))
Output:
making 1
first: 1
Generator expressions and memory
A generator expression looks like a list comprehension with ( ) instead of [ ]. It does not build the list in memory.
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) > 8_000_000) # True (over 8 MB)
print(sys.getsizeof(squares_gen) < 500) # True (a few hundred bytes)
print(sum(n * n for n in range(5))) # 30 (no extra brackets needed)
yield from
yield from other hands out every item of another iterable (or generator), one by one.
def morning():
yield "Asha"
yield "Ravi"
def all_shifts():
yield from morning()
yield from ["Meera", "Kiran"]
print(list(all_shifts())) # ['Asha', 'Ravi', 'Meera', 'Kiran']
A pipeline of generators
Chain small generators: each one takes an iterable and yields cleaned-up items. Only one line is in memory at a time, so this works even on a 10 GB log file.
Real-world example: read lines → skip blanks/comments → parse → keep errors.
lines = ["# server log", "GET /home 200", "", "GET /cart 500", "POST /pay 404"]
def skip_noise(rows):
for row in rows:
if row and not row.startswith("#"):
yield row
def parse(rows):
for row in rows:
method, path, status = row.split()
yield {"path": path, "status": int(status)}
def errors_only(requests):
for r in requests:
if r["status"] >= 400:
yield r
pipeline = errors_only(parse(skip_noise(lines)))
for r in pipeline:
print(r)
Output:
{'path': '/cart', 'status': 500}
{'path': '/pay', 'status': 404}
In a real program, the first step reads a file line by line (for line in file: yield line). See Section 11.
🔍 Going deeper: a
returninside a generator ends it (it raisesStopIterationfor you). Generators can also receive values with.send(), which is rarely needed.
Full program: examples/04_iterators_and_generators.py.
Done here? The practice set for Part 10 — 8 exercises with solutions — is on the part page.