Advertisement
Beginner Python, Async Generators & Async Context Managers

What is an async context manager, and which two dunder methods does it require?

Short answer

An async context manager implements __aenter__ and __aexit__ (both coroutines, defined with 'async def') instead of the synchronous __enter__/__exit__ — used with 'async with' to manage a resource whose setup or teardown itself requires awaiting, like an async database…

Save Python mock interview
Advertisement
AModel answer
An async context manager implements __aenter__ and __aexit__ (both coroutines, defined with 'async def') instead of the synchronous __enter__/__exit__ — used with 'async with' to manage a resource whose setup or teardown itself requires awaiting, like an async database connection.
class AsyncConnection:
    async def __aenter__(self):
        await self.connect()
        return self
    async def __aexit__(self, exc_type, exc, tb):
        await self.disconnect()

async def main():
    async with AsyncConnection() as conn:
        await conn.query("SELECT 1")
Real-world example
Managing an async database or HTTP client session where opening/closing the connection are themselves async operations.
Likely follow-ups
  • What happens to __aexit__ if an exception is raised inside the 'async with' block?
Related topics