Sub topic 13
Delegating to sub-generators with yield from
This chapter assumes you can write generator functions with yield and know that a generator raises StopIteration when it finishes. It covers yield from, which lets one generator hand work to another.
The problem: forwarding values by hand
Suppose a generator needs to produce every value from another iterable before continuing. The obvious way is a loop:
def chain_manual(first, second):
for item in first:
yield item
for item in second:
yield item
print(list(chain_manual([1, 2], "ab"))) # [1, 2, 'a', 'b']yield from replaces each of those loops with one statement:
def chain(first, second):
yield from first
yield from second
print(list(chain([1, 2], "ab"))) # [1, 2, 'a', 'b']The expression after yield from can be any iterable: a list, a string, an iterator, or another generator. The outer generator pauses while the sub-iterable produces values. Each value goes straight to whoever called next() on the outer generator.
Recursion with yield from
yield from is most useful when a generator calls itself. Flattening a nested list is the standard example:
def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print(list(flatten([1, [2, [3, 4]], 5]))) # [1, 2, 3, 4, 5]Each nested list gets its own generator object. The caller still sees one flat stream.
What the diagram shows
When the caller asks for the next value, the request passes through the outer generator to the inner one. The inner generator's values come back out the same way.
The value of a yield from expression
yield from is also an expression. Its value is the sub-generator's return value, which Python carries in StopIteration.value:
def inner():
yield 1
yield 2
return "done"
def outer():
result = yield from inner()
print(result)
print(list(outer())) # prints "done", then [1, 2]The string "done" never appears in the list, because list() only collects yielded values. Only the delegating generator sees it, through result. This lets a sub-generator pass back a summary, such as a count or a status, after it has yielded its items.
More than a shortcut
yield from does more than the for loop version. It also forwards send(), throw() and close() calls to the sub-generator. A hand-written loop would swallow those calls. The final chapter covers two-way communication in detail. For now, remember that yield from creates a transparent channel between the caller and the inner generator.
Common mistakes
- Writing
yield gen()instead ofyield from gen(). The first yields the generator object itself as a single value. The second yields its items. - Expecting the return value in the output. A
returnvalue is not yielded. Capture it withresult = yield from .... - Using
yield fromon a non-iterable.yield from 5raisesTypeError, just likefor x in 5.
Exercise
What does this code print? def letters(): yield "a" return 3 def wrapper(): n = yield from letters() yield n * 2 print(list(wrapper()))
Show answer
It prints ['a', 6]. yield from letters() passes "a" to the caller. When letters() returns 3, that value becomes n, and wrapper() then yields 3 * 2 = 6.