Search⌘ K
AI Features

... continued

Explore the use of yield from to return values from subgenerators and how it applies to generator-based coroutines, native coroutines, and futures in Python's Async.io. Understand how these constructs interact through iteration protocols and prepare to handle asynchronous programming effectively.

We'll cover the following...

Returning Values from Yield from

yield from can also receive the value returned by the subgenerator. Consider the example below. The nested_generator() returns the value 999 and is printed by the outer_generator().

def nested_generator():
    i = 0
    while i < 5:
        i += 1
        yield i
    
    # return a value from the sub-generator
    return 999


def outer_generator():
    nested_gen = nested_generator()
    # outer generator receives the return value of the sub-generator
    ret_val = yield from nested_gen
    print("received in outer generator: " + str(ret_val))


if __name__ == "__main__":

    gen = outer_generator()

    for item in gen:
        print(item)

Python 3.5
def nested_generator():
i = 0
while i < 5:
i += 1
yield i
return 999
def outer_generator():
nested_gen = nested_generator()
ret_val = yield from nested_gen
print("received in outer generator: " + str(ret_val))
if __name__ == "__main__":
gen = outer_generator()
for item in gen:
print(item)
...