Sub topic 3
Chaining Generators into Pipelines
Assume you know Python functions, loops, exceptions, and basic collections. A generator pipeline connects stages so each stage receives one value and yields one value at a time.
Chaining generators
def non_empty(lines):
for line in lines:
if line.strip():
yield line
def shout(lines):
for line in lines:
yield line.strip().upper()
pipeline = shout(non_empty(["hello", "", "world"]))
print(list(pipeline)) # ['HELLO', 'WORLD']Each stage is lazy. No line is processed until list() requests values.
Exhaustion and useful tools
An iterator is single-use. After it reaches StopIteration, repeating the loop produces no values.
The itertools module provides efficient building blocks. islice safely takes part of an infinite stream:
from itertools import islice
def count_up():
number = 0
while True:
yield number
number += 1
print(list(islice(count_up(), 4))) # [0, 1, 2, 3]For read loops, iter(callable, sentinel) repeatedly calls a function until it returns the sentinel:
from io import StringIO
stream = StringIO("abcdef")
for chunk in iter(lambda: stream.read(2), ""):
print(chunk) # ab, cd, efDelegation and generator control
yield from forwards values from another generator. Its expression also receives the sub-generator's return value.
def inner():
yield 1
return "finished"
def outer():
result = yield from inner()
print(result)
print(list(outer())) # finished, then [1]A generator can receive input through send(). The first next() starts it. throw() injects an exception at the pause point, and close() asks it to stop.
def total():
value = 0
try:
while True:
value += yield value
except GeneratorExit:
print("closed")
g = total()
next(g) # 0
print(g.send(5)) # 5
g.close()Exercise
Why does a second list() call on the same generator return an empty list?
Show answer
The first call exhausts the single-use iterator, so it has no values left.