Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

Asynchronous Generators in Python

Give Feedback

In this lesson you’ll learn how to create an asynchronous generator:

async def square_odds(start, stop):
    for odd in odds(start, stop):
        await asyncio.sleep(2)
        yield odd ** 2

You’ll also see how to loop over values asynchronously using an async for loop.

Comments & Discussion

karncx on Aug. 30, 2019

Why does the async for take number of steps * 2 seconds? Why does it not save time like asyncio.gather?

tevakrief on Sept. 12, 2019

Hello ! Same question as karncx, why does it take 2s each time ?

Thanks !

Hilman on Feb. 8, 2020

My understanding is that asyncio.gather is the one that responsible for the coroutine which basically means, do the tasks together. As for the asynchronous generator, it just show an example of one async task (a generator in this case).

You can try to run multiple asynchronous coroutine-ly. Maybe change the code to something like this:

async def square_odds(start, stop):
    for odd in odds(start, stop):
        await asyncio.sleep(2)  # talking to database simulation
        yield odd ** 2

async def for_async(func_id):
    async for so in square_odds(11, 17):
        print(f"({func_id}) so: {so}")

await asyncio.gather(*(for_async(f"for_loop {i}") for i in range(3)))

Become a Member to join the conversation.