What does `yield from` do, and what problem did it solve compared to manually looping and re-yielding?
Answer
`yield from subgenerator` delegates iteration to `subgenerator`, transparently yielding every value it produces as if the outer generator had yielded them directly, and it also forwards `send()`, `throw()` and `close()` calls down to the subgenerator and propagates its return value back as the value of the `yield from` expression. Before PEP 380 introduced it in Python 3.3, delegating to a subgenerator required a manual `for item in subgenerator: yield item` loop, which loses the ability to properly forward sent values, thrown exceptions and the subgenerator's return value.
Strong answer includes
- delegates iteration, sending, throwing and closing to a subgenerator
- yield from expression evaluates to the subgenerator's return value
- replaces an error-prone manual for-loop-and-yield pattern
Practical example
def all_lines(files):
for path in files:
yield from open(path)streams every line from every file in sequence without manually re-yielding each one.