Async

Async Iteration and Context

async for and async with consume asynchronous streams and cleanup protocols.

An async generator can await before yielding each value. async for consumes those values with the asynchronous iteration protocol.

Source

import asyncio

async def titles():
    for slug in ["values", "async-await"]:
        await asyncio.sleep(0)
        yield slug.replace("-", " ").title()

print(titles.__name__)

Output

titles
LOOPCOROawaitresume
async iteration and async with both rest on the same loop-vs-coroutine handoff as await.

An async context manager defines __aenter__ and __aexit__. async with awaits setup and cleanup around the block.

Source

class Session:
    async def __aenter__(self):
        print("open")
        return self

    async def __aexit__(self, exc_type, exc, tb):
        print("close")

print(Session.__name__)

Output

Session

The top-level coroutine combines both protocols: open the async resource, then consume the async stream inside it.

Source

async def main():
    async with Session():
        async for title in titles():
            print(title)

asyncio.run(main())

Output

open
Values
Async Await
close

Notes

See also

Run the complete example

Example code

Expected output

open
Values
Async Await
close

Execution time appears here after you run the example.