Async Context Managers and Iterators
Implement async with and async for protocols.
async with Statement
Use async with for context managers whose setup/teardown involves awaiting I/O. The managed object must implement __aenter__ and __aexit__.
import asyncio
class AsyncFile:
async def __aenter__(self):
print("open")
return self
async def __aexit__(self, *args):
print("close")
async def main():
async with AsyncFile() as f:
print("using")
asyncio.run(main())__aenter__ and __aexit__
Both are coroutines. __aenter__ is awaited on entry; __aexit__ is awaited on exit even if an exception occurred.
import asyncio
class DBSession:
async def __aenter__(self):
self.conn = await async_connect()
return self.conn
async def __aexit__(self, exc_type, exc_val, exc_tb):
if exc_type:
await self.conn.rollback()
else:
await self.conn.commit()
await self.conn.close()
return FalseAll lessons in this course
- Coroutines and the event loop
- await, Tasks, and Gathering
- Async Context Managers and Iterators
- Async I/O Patterns in Production