Join my Laravel for REST API's course on Udemy 👀

Async generator functions in Python

September 22, 2021  ‐ 1 min read

Asynchronous generator functions are part of Python version 3.6, they were introduced by PEP-525. Asynchronous generator functions are much like regular asynchronous functions except that they contain the yield keyword in the function body. Which in turn, makes them much like regular generators, except for that you can use the await keyword in there as well.

When calling an asynchronous generator function, the result that is returned is an asynchronous generator object. In contrast to calling regular asynchronous functions which return a coroutine object.

async def async_generator():
    yield

print(async_generator())
# => <async_generator object async_generator at 0x7f4eb88b5c10>

async def async_function():
    pass

print(async_function())
# => <coroutine object async_function at 0x7f4eb8f52d40>

Since the asynchronous generator is, no surprise, asynchronous you are allowed to use the await keyword inside the asynchronous generator.

You can use this, for example, to send out HTTP requests in the asynchronous generator and yielding the response.

async def download_pages(urls):
    for url in urls:
        response = await get_response(url)
        yield response

Besides asynchronous iterables you can use asynchronous generators with the async for-loop as well.