Async
Async Iteration and Context
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
titlesAn 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
SessionThe 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
closeNotes
async forconsumes asynchronous iterators.async withawaits asynchronous setup and cleanup.- These forms are common around I/O-shaped resources.
See also
- prerequisite: Async Await
- prerequisite: Iterators
- prerequisite: Context Managers
Run the complete example
Expected output
open
Values
Async Await
close
Execution time appears here after you run the example.