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
:
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:
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))
The first line of main
delegates into the internal generator and produces the values, extracting them directly from it. This is nothing new, as we have already seen. Notice, though, how the sequence()
generator function returns the end value, which is assigned in the first line to the variable named step1
, and how this value is correctly used at the start of the following instance of that generator. ...