Delegating Generators with yield from
1Concept
`yield from <iterable>` delegates generator execution to a sub-generator. It flattens nested iterables and transparently establishes a two-way communication channel passing `.send()` and `.throw()` between the caller and sub-generator.
2Architecture Diagram
Outer Generator ---> yield from Sub-Generator ---> Directly Streams Values to Client
3Code Example
Python 3.12
def sub_task(prefix: str, count: int):
for i in range(1, count + 1):
yield f"{prefix}-{i}"
def master_pipeline():
yield from sub_task("Ingest", 2)
yield from sub_task("Transform", 2)
yield from sub_task("Export", 1)
print(f"Pipeline stages: {list(master_pipeline())}")4Expected Output
Pipeline stages: ['Ingest-1', 'Ingest-2', 'Transform-1', 'Transform-2', 'Export-1']
5Key Takeaways
- ✓`yield from` replaces verbose nested loops (`for x in subgen: yield x`).
- ✓Establishes a bi-directional data channel between delegating caller and sub-generators.
- ✓The return value of the sub-generator (`return val`) becomes the value of the `yield from` expression.