Sub topic 13
Delegating to sub-generators with yield from
This chapter assumes you can write generator functions with yield, know that a generator is an iterator, and understand how StopIteration ends a loop. Send, throw and return values appear only as far as yield from needs them.
The problem: forwarding values by hand
A generator often needs to produce everything another iterable produces before it continues. The obvious code is a loop:
def chain_manual(a, b):
for item in a:
yield item
for item in b:
yield item
print(list(chain_manual([1, 2], "xy"))) # [1, 2, 'x', 'y']yield from replaces each of those loops with one statement:
def chain(a, b):
yield from a
yield from b
print(list(chain([1, 2], "xy"))) # [1, 2, 'x', 'y']The expression after yield from can be any iterable: a list, a string, a file, or another generator. Python calls iter() on it and passes each value to your caller. The outer generator is suspended while the delegation runs. When the inner iterator is exhausted, execution continues on the next line.
Delegation is more than a loop
For plain iterables, yield from x and for v in x: yield v give the same sequence of values. The difference appears when the inner object is a generator. yield from opens a two-way channel between the caller and the sub-generator:
| Feature | `for v in sub: yield v` | `yield from sub` |
|---|---|---|
| Values reach the caller | Yes | Yes |
| `send(x)` reaches `sub` | No, the value arrives at the outer `yield` and is discarded | Yes |
| `throw(exc)` reaches `sub` | No, it is raised in the outer generator | Yes |
| `close()` closes `sub` | Only when the outer generator is cleaned up | Yes |
| `sub`'s return value | Lost | Becomes the value of the expression |
While the delegation is active, the outer generator does not run any of its own code. Each next() call goes straight to the inner generator.
Recursion: walking a tree
The most common use is a recursive generator. Without yield from, every level of recursion needs its own loop:
from dataclasses import dataclass, field
@dataclass
class Node:
value: str
children: list = field(default_factory=list)
def walk(node):
yield node.value
for child in node.children:
yield from walk(child)
tree = Node("root", [
Node("a", [Node("a1"), Node("a2")]),
Node("b"),
])
print(list(walk(tree))) # ['root', 'a', 'a1', 'a2', 'b']This is a depth-first, pre-order traversal. The values are produced lazily, so a consumer that stops early never visits the rest of the tree.
Calling walk(child) on its own only creates a generator object and runs nothing. If you wrote walk(child) without yield from, the children would be silently skipped. This is a common bug.
Flattening nested lists
Flattening is the same pattern. It has one trap, which is strings:
def flatten(items):
for item in items:
if isinstance(item, (list, tuple)):
yield from flatten(item)
else:
yield item
print(list(flatten([1, [2, [3, 4]], "ab"]))) # [1, 2, 3, 4, 'ab']The check names list and tuple on purpose. Strings are iterable, and each character of a string is itself a one-character string. A check such as "is this iterable?" would recurse forever on "a".
Return values
A generator can return a value. The value travels inside StopIteration, and ordinary for loops and list() ignore it. yield from catches it and hands it to you as the value of the expression:
def numbered(items):
count = 0
for item in items:
yield item
count += 1
return count
def report(items):
total = yield from numbered(items)
yield f"total={total}"
print(list(report("ab"))) # ['a', 'b', 'total=2']This lets a sub-generator stream its values to the caller and also report a final result to its parent. The caller of report never sees the count except as the last item the parent chooses to yield.
Without yield from, you would have to catch the exception yourself:
gen = numbered("ab")
try:
while True:
next(gen)
except StopIteration as stop:
print(stop.value) # 2yield from does this work for you, which is why it is the normal way to consume a return value.
Sending and throwing through the delegation
When the caller uses send(), the value goes to the innermost active generator:
def inner():
received = yield "ready"
print("inner got", received)
return received
def outer():
result = yield from inner()
yield f"outer saw {result}"
g = outer()
print(next(g)) # ready
print(g.send("hi")) # prints "inner got hi", then "outer saw hi"The first next() runs outer until it enters inner, which yields "ready". The send("hi") call skips outer and resumes inner directly. inner returns, outer resumes with result == "hi", and it yields the next value.
throw() and close() follow the same route. An exception thrown into outer while it is delegating is raised at the yield inside inner. If inner handles it and continues, the delegation carries on. If inner lets it escape, it propagates out through outer. Calling close() on outer closes inner first.
Splitting a generator into parts
yield from lets you break a long generator into named stages without changing what the caller sees. Here, one parser handles a header and then the body, and both stages share a single iterator:
def header(it):
line = next(it)
yield f"columns: {line}"
return line.split(",")
def parse(lines):
it = iter(lines)
columns = yield from header(it)
for line in it:
yield dict(zip(columns, line.split(",")))
data = ["id,name", "1,Ann", "2,Bo"]
for item in parse(data):
print(item)
# columns: id,name
# {'id': '1', 'name': 'Ann'}
# {'id': '2', 'name': 'Bo'}The call iter(lines) matters. Both generators must consume the same iterator object. If you passed a list to header and called next() on it, you would get a TypeError, because a list is an iterable and not an iterator.
Common errors
- Forgetting
yield fromon a recursive call.walk(child)alone creates a generator and discards it. No error is raised, and the output is missing items. - Using
yieldinstead ofyield from.yield walk(child)produces the generator object itself as one item, not its contents. - Delegating to a non-iterable.
yield from 5raisesTypeError: 'int' object is not iterable. - Using
yield fromoutside a generator. It is only valid inside a function body. Using it inside a list comprehension, or in a lambda, is aSyntaxError. - Exhausted iterators.
yield from itconsumesit. A secondyield from iton the same iterator produces nothing. If you need to repeat, delegate to a re-iterable object such as a list or an instance of a class whose__iter__returns a fresh iterator. - Ignoring the return value.
list(report("ab"))gets the yielded values only. Only ayield fromor a manualStopIterationhandler sees the return value. - Deep recursion. Each level of a recursive
yield fromis a live generator frame. A tree or nested list with more than about 1000 levels hits Python's default recursion limit and raisesRecursionError. Every value also passes through every level above the one that produced it, so the cost per item grows with depth. For very deep structures, use an explicit stack in one generator.
When to choose yield from
- Use it when a generator should emit everything from another iterable, and you would otherwise write a one-line
forloop that only yields. - Use it for recursive traversals.
- Use it when you need the sub-generator's return value.
- Keep the
forloop when you transform or filter each item (yield item * 2), becauseyield fromcannot change the values passing through. Use a generator expression or a small stage generator for that.
Exercise
What does this program print, and why? def inner(): yield 1 return "r" def outer(): value = yield from inner() yield value print(list(outer()))
Show answer
It prints [1, 'r']. The yield from passes 1 to the caller, then inner returns "r". That return value becomes the value of the yield from expression, so value is "r", and outer yields it as its second item.
Exercise
This function should list every file path under a nested dictionary, where dictionary values are either a string (a file) or another dictionary (a folder). The output is empty for nested folders. Fix it. def paths(tree, prefix=""): for name, value in tree.items(): if isinstance(value, dict): paths(value, prefix + name + "/") else: yield prefix + name
Show answer
The recursive call creates a generator and discards it, so nested files are never produced. Delegate with yield from:
def paths(tree, prefix=""):
for name, value in tree.items():
if isinstance(value, dict):
yield from paths(value, prefix + name + "/")
else:
yield prefix + name