yield from in Python
Delegating iteration to a sub-generator, for recursion.
def walk(node):
yield node["name"]
for child in node.get("children", []):
yield from walk(child)
tree = {
"name": "root",
"children": [
{"name": "src", "children": [{"name": "app.py"}]},
{"name": "README.md"},
],
}
names = list(walk(tree))
How it works
yield from walk(child)re-emits a child's values.- It flattens a recursive tree walk cleanly.
listcollects every name in visit order.
Keywords and builtins used here
defforlistwalkyield
The run, in numbers
- Lines
- 15
- Characters to type
- 242
- Tokens
- 97
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 58 seconds.
Step 2 of 5 in Generators & itertools, step 11 of 53 in Pythonic Python.