Yield From
This lesson explains the yield from syntax.
We'll cover the following...
Yield From
The yield from
syntax was introduced in PEP-380. The stated motivation for introducing the syntax is to enable refactoring of existing code that utilizes yield
easier. The yield from syntax is as follows:
yield from <expr>
The expression must be an iterable from which an iterator is extracted. Let's understand the problem that yield from
solves. Consider the following snippet of code:
def nested_generator():
i = 0
while i < 5:
i += 1
yield i
def outer_generator():
nested_gen = nested_generator()
for item in nested_gen:
yield item
if __name__ == "__main__":
gen = outer_generator()
for item in gen:
print(item)
The above code has two generator functions. The outer_generator()
calls the nested_generator()
in a loop and returns values from the inner generator to the main script. You can run the code below and examine the output.
Press + to interact
def nested_generator():i = 0while i < 5:i += 1yield idef outer_generator():nested_gen = nested_generator()for item in nested_gen:yield itemif __name__ == "__main__":gen = outer_generator()for item in gen:print(item)
We can refactor the above code and remove the for loop in the outer_generator()
as follows, with the same output.
def nested_generator():
i = 0
while i < 5:
i += 1
yield i
def outer_generator_with_yield_from():
nested_gen =