Sub topic 12
async with and asynchronous context managers
This chapter assumes you know how with, __enter__ and __exit__ work, and how @contextmanager generators work. It also assumes you have used async def and await in basic asyncio code.
Why a second protocol exists
Setup and cleanup sometimes need to wait. Opening a database connection, releasing a network lock, or flushing a buffer to a remote server can all be await calls. A normal __enter__ or __exit__ is an ordinary method. It cannot use await, and blocking inside it would stall the whole event loop.
Python solves this with a parallel protocol. async with calls __aenter__ and __aexit__, and both are coroutines, so Python awaits them.
| Synchronous | Asynchronous |
|---|---|
| `with` | `async with` |
| `__enter__` | `async def __aenter__` |
| `__exit__` | `async def __aexit__` |
| `@contextmanager` | `@asynccontextmanager` |
| `ExitStack` | `AsyncExitStack` |
The rules for the exception arguments and for suppression are the same as before. __aexit__ receives the exception type, value and traceback. A true return value suppresses the exception.
The order of events
While either method is suspended at an await, the event loop can run other tasks. That is the main benefit over the synchronous form.
A class-based asynchronous manager
import asyncio
class Connection:
async def __aenter__(self):
await asyncio.sleep(0.1) # simulate connecting
print("connected")
return self
async def __aexit__(self, exc_type, exc_value, traceback):
await asyncio.sleep(0.1) # simulate a graceful disconnect
print("disconnected")
return False # do not suppress exceptions
async def main():
try:
async with Connection() as conn:
print("working with", conn)
raise RuntimeError("query failed")
except RuntimeError as error:
print("caught:", error)
asyncio.run(main())The output is connected, working with ..., disconnected, and then caught: query failed. The disconnect runs before the exception reaches the except clause, exactly as __exit__ would.
A generator-based asynchronous manager
For most code, contextlib.asynccontextmanager is shorter. You write an async def generator with a single yield.
import asyncio
from contextlib import asynccontextmanager
@asynccontextmanager
async def session(name):
print(f"open {name}")
try:
yield name
finally:
await asyncio.sleep(0) # an awaited cleanup step
print(f"close {name}")
async def main():
async with session("db") as s:
print("using", s)
asyncio.run(main())As in the synchronous version, wrap the yield in try/finally. Without it, an exception in the body skips the cleanup code.
Where you meet async managers
The standard library and common packages use async with in several places:
asyncio.Lock,asyncio.Semaphoreand other synchronization primitives.asyncio.timeout(...), which cancels the body if it runs too long (Python 3.11+).asyncio.TaskGroup(), which waits for all child tasks on exit (Python 3.11+).- Client sessions and database connection pools in third-party libraries.
You can put several managers in one statement, as with with: async with a() as x, b() as y:. For a number of managers that is only known at run time, use contextlib.AsyncExitStack.
Common mistakes
Using the wrong keyword fails at run time. A plain with on an object that only defines __aenter__ raises a TypeError. An async with on an object that only defines __enter__ fails the same way. Some objects, such as asyncio.Lock, support only the async form.
Cleanup can also be cancelled. If the task is cancelled while __aexit__ is awaiting, the rest of the cleanup may not run. Keep awaited cleanup short, and use asyncio.shield for steps that must finish.
Exercise
You write a class with __enter__ and __exit__ that calls await connection.close() inside __exit__. What is wrong, and how do you fix it?
Show answer
await is a syntax error in a normal method, and a synchronous __exit__ cannot wait for a coroutine. Rename the methods to async def __aenter__ and async def __aexit__, then use the class with async with inside an async def function.