Sub topic 12
async with and Asynchronous Context Managers
This chapter assumes you know the with statement, the __enter__/__exit__ protocol, and @contextmanager. It also assumes basic asyncio: async def, await, and asyncio.run. The examples use Python 3.11 or newer.
Why a plain with statement is not enough
Some setup and cleanup work has to wait for I/O. Opening a network connection, releasing a distributed lock, and flushing a buffer to a remote service all involve await. __enter__ and __exit__ are ordinary functions, so they cannot await anything. Calling blocking code inside them would freeze the whole event loop.
Python solves this with a second protocol and a second statement, async with. It has the same guarantee as with: cleanup runs however the block ends. The difference is that setup and cleanup are coroutines, so they can suspend while the event loop runs other tasks.
| Aspect | `with` | `async with` |
|---|---|---|
| Setup method | `__enter__` | `async def __aenter__` |
| Cleanup method | `__exit__` | `async def __aexit__` |
| Generator helper | `@contextmanager` | `@asynccontextmanager` |
| Dynamic composition | `ExitStack` | `AsyncExitStack` |
| Allowed in | any code | `async def` only |
The protocol: __aenter__ and __aexit__
Python awaits __aenter__ when the block starts. The awaited result goes to the as name. When the block ends, Python awaits __aexit__ with the same three arguments as __exit__: exception type, exception value, and traceback. All three are None when the block finished normally.
import asyncio
class Connection:
def __init__(self, name):
self.name = name
async def __aenter__(self):
print(f"connecting to {self.name}")
await asyncio.sleep(0.1) # stands in for a network handshake
return self
async def __aexit__(self, exc_type, exc_value, traceback):
print(f"closing {self.name}")
await asyncio.sleep(0.1) # stands in for a graceful shutdown
return False # do not suppress exceptions
async def query(self, sql):
await asyncio.sleep(0.05)
return f"result of {sql!r}"
async def main():
async with Connection("db") as conn:
print(await conn.query("SELECT 1"))
asyncio.run(main())The output is connecting to db, then result of 'SELECT 1', then closing db.
Exceptions and suppression
The rules match the synchronous protocol. If __aexit__ returns a true value after an exception, Python suppresses that exception. Otherwise it re-raises the exception after __aexit__ finishes. Python awaits __aexit__ before deciding, so the method can do asynchronous work first.
import asyncio
class IgnoreAsync:
def __init__(self, *exc_types):
self.exc_types = exc_types
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_value, traceback):
await asyncio.sleep(0) # an await is allowed here
return exc_type is not None and issubclass(exc_type, self.exc_types)
async def main():
async with IgnoreAsync(KeyError):
raise KeyError("missing")
print("continues after KeyError")
try:
async with IgnoreAsync(KeyError):
raise ValueError("bad")
except ValueError:
print("ValueError propagated")
asyncio.run(main())Never raise a new exception from __aexit__ unless you mean to replace the original one. Python chains the original as __context__, but the caller sees only the new exception type.
Generator style with @asynccontextmanager
contextlib.asynccontextmanager turns an async generator into an async context manager. The code before yield is the setup. The yielded value goes to as. The code after yield is the cleanup. As with @contextmanager, an exception in the block is thrown into the generator at the yield, so you handle it with try, except, and finally around that line.
import asyncio
from contextlib import asynccontextmanager
@asynccontextmanager
async def transaction(log):
log.append("begin")
try:
yield log
except BaseException:
await asyncio.sleep(0) # for example, await a rollback call
log.append("rollback")
raise
else:
await asyncio.sleep(0) # for example, await a commit call
log.append("commit")
async def main():
log = []
async with transaction(log) as tx:
tx.append("insert row")
try:
async with transaction(log) as tx:
raise RuntimeError("boom")
except RuntimeError:
pass
print(log)
asyncio.run(main())This prints ['begin', 'insert row', 'commit', 'begin', 'rollback']. The failing block is rolled back, and the raise re-raises the original error.
The generator must yield exactly once. If it yields a second time, or yields after swallowing an exception it should have re-raised, Python raises RuntimeError.
Context managers you already use in async code
Much of asyncio is built on async with. The first three examples are from the standard library:
asyncio.Lock,asyncio.Semaphore, andasyncio.Conditionacquire in__aenter__and release in__aexit__.asyncio.TaskGroup(3.11+) waits for all child tasks on exit and cancels the siblings if one fails.asyncio.timeout()(3.11+) cancels the block when a deadline passes.- Third-party libraries, such as HTTP clients and database drivers, use
async withfor sessions, connections, and transactions.
import asyncio
async def main():
try:
async with asyncio.timeout(0.1):
await asyncio.sleep(1)
except TimeoutError:
print("timed out")
asyncio.run(main())asyncio.timeout works because __aexit__ can see the CancelledError that the deadline injected into the block. It converts that error into a TimeoutError. This is a good example of why __aexit__ receives the exception instead of just being a finally block.
Cancellation and cleanup
Cancellation is the main thing that makes async cleanup different. When a task is cancelled, asyncio raises CancelledError at the task's current await. The async with machinery then calls __aexit__ as usual, so cleanup still runs.
import asyncio
from contextlib import asynccontextmanager
@asynccontextmanager
async def session(name):
print(f"open {name}")
try:
yield name
finally:
print(f"close {name}")
async def job():
async with session("db"):
await asyncio.sleep(10)
async def main():
task = asyncio.create_task(job())
await asyncio.sleep(0.1)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("cancelled")
asyncio.run(main())The output is open db, close db, cancelled. Two details matter when you write your own managers.
First, CancelledError derives from BaseException, not Exception. A handler written as except Exception: will not run on cancellation. That is why transaction above catches BaseException. Use finally when cleanup must happen in every case.
Second, cleanup that awaits can itself be cancelled. If the task receives a second cancellation while __aexit__ is suspended, the cleanup stops partway. For cleanup that must finish, such as releasing a remote lock, wrap the critical call in asyncio.shield:
import asyncio
class Resource:
async def _close(self):
await asyncio.sleep(0.1)
print("closed")
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc_value, traceback):
await asyncio.shield(self._close())
async def main():
async with Resource():
print("working")
asyncio.run(main())shield lets the inner coroutine keep running even if the outer await is cancelled. The caller still sees the CancelledError, so the cancellation is not lost.
Several managers, and mixing sync with async
One async with statement can hold several managers, separated by commas. They are entered left to right and exited in reverse order:
async with Connection("a") as a, Connection("b") as b:
...Every item in an async with statement must be an async context manager. To combine a synchronous and an asynchronous manager, nest the statements:
async with Connection("db") as conn:
with open("log.txt", "w") as log:
log.write(await conn.query("SELECT 1"))For a number of managers that is only known at run time, use contextlib.AsyncExitStack. It offers enter_async_context for async managers, enter_context for ordinary ones, and push_async_callback for arbitrary cleanup coroutines.
import asyncio
from contextlib import AsyncExitStack, asynccontextmanager
@asynccontextmanager
async def session(name):
print(f"open {name}")
try:
yield name
finally:
print(f"close {name}")
async def main():
async with AsyncExitStack() as stack:
names = [await stack.enter_async_context(session(n)) for n in ("a", "b", "c")]
print("using", names)
asyncio.run(main())The output is open a, open b, open c, using ['a', 'b', 'c'], then close c, close b, close a.
A few other helpers have async forms. contextlib.aclosing(obj) awaits obj.aclose() on exit. It is the right way to guarantee that an async generator is finalized. contextlib.nullcontext() can be used with async with from Python 3.10, which helps when a manager is optional.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `SyntaxError: 'async with' outside async function` | `async with` used in a normal function or at module level | Move the code into an `async def`. Alternatively, run it in the `python -m asyncio` REPL |
| `TypeError` mentioning the asynchronous context manager protocol | The object has no `__aenter__` or `__aexit__`, or `__aexit__` was written as a plain `def` | Define both methods with `async def` |
| `TypeError` when using plain `with` on an async manager | The object only implements the async protocol | Use `async with` |
| `RuntimeError: generator didn't stop` | The `@asynccontextmanager` generator yielded more than once | Yield exactly once |
| Event loop stalls during setup | A blocking call, such as `time.sleep` or a synchronous driver, inside `__aenter__` | Use an async API, or move the call to a thread with `asyncio.to_thread` |
| Cleanup skipped on cancellation | The handler catches `Exception` only | Use `finally` or `except BaseException` |
| `RuntimeError` on reuse | A manager made by `@asynccontextmanager` was entered twice | Call the function again to get a new one |
Test async managers by driving them from asyncio.run or from your test framework's async support, and assert on a recorded list of events, as the transaction example does. Check three paths: normal exit, an exception in the block, and cancellation.
Exercise
A class defines async def __aexit__(self, *exc): await self.conn.close() and nothing else about exceptions. A block using it raises ValueError. What happens to the ValueError after __aexit__ completes, and why?
Show answer
The ValueError propagates to the caller. __aexit__ returns None, which is falsy, so Python does not suppress the exception. The close still runs first, because Python awaits __aexit__ before re-raising.
Exercise
You write an @asynccontextmanager function that acquires a remote lock before yield and releases it after yield with await lock.release(), with no try or finally. What goes wrong when the block raises an exception or the task is cancelled, and how do you fix it?
Show answer
The exception (or CancelledError) is thrown into the generator at the yield. Without try/finally, it propagates out immediately and the await lock.release() line never runs, so the lock leaks. Fix it by wrapping the yield: try: yield ... finally: await lock.release(). For release that must survive a second cancellation, use await asyncio.shield(lock.release()).