Further Uses of the yield from Construction
Learn more about the yield from construction in Python.
We'll cover the following...
Let's explore the real use of the yield from
construction.
Capturing the value returned by a subgenerator
In the following example, we have a generator that calls another two nested generators, producing values in a sequence. Each one of these nested generators returns a value, and we will see how the top-level generator is able to effectively capture the return value since it's calling the internal generators through yield from
:
Press + to interact
main.py
log.py
from log import loggerdef sequence(name, start, end):logger.info("%s started at %i", name, start)yield from range(start, end)logger.info("%s finished at %i", name, end)return enddef main():step1 = yield from sequence("first", 0, 5)step2 = yield from sequence("second", step1, 10)return step1 + step2
This is a possible execution of the code in main
while it's being iterated:
Press + to interact
g = main()print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))
...