How to Delegate Iteration to a Subgenerator with yield from in Python
Use yield from to delegate iteration from one generator to a subgenerator, flattening nested generator output into a single sequence.
Python code
15 linesdef subgenerator():
yield "first"
yield "second"
yield "third"
def delegate():
yield "before delegation"
yield from subgenerator()
yield "after delegation"
if __name__ == "__main__":
for item in delegate():
print(item)
Output
before delegation
first
second
third
after delegation
How it works
The yield from expression forwards yielded values from the subgenerator to the caller, making the outer generator behave as if its body were spliced into the delegating generator. It also forwards send() and throw() calls, so the delegation is transparent for advanced generator protocols. This pattern reduces nested loops and keeps generator code readable when composing multiple generators.
Common mistakes
- Using `yield from` with a non-iterable argument instead of a generator/iterable
- Forgetting that `yield from` can only be used inside a generator function
- Confusing `yield from` with `return from` — it never returns the subgenerator's value
Variations
- Chain multiple generators: `yield from gen1; yield from gen2`
- Use `yield from` with lists or other iterables to flatten them into the generator stream
Real-world use cases
- Composing multiple pipeline stages where each stage is a generator that processes data incrementally.
- Building a CLI tool that concatenates multiple log files by delegating to per-file parsers.
- Implementing a recursive generator that yields items from nested tree structures with minimal boilerplate.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.