async with is the asynchronous version of the with statement. It enters an asynchronous context manager by awaiting __aenter__() and leaves it by awaiting __aexit__(), so setup and cleanup can themselves wait on I/O without blocking the event loop. Use it for connections, locks, sessions, transactions and files in async def code.
Like a normal with block, the cleanup runs even when the body raises an exception, which makes it the safest way to release resources.
An asynchronous context manager is any object that defines two coroutine methods:
__aenter__(self): awaited when the block starts. Its return value is bound to the name after as.__aexit__(self, exc_type, exc_value, traceback): awaited when the block ends, normally or through an exception. Return a true value to suppress the exception; return None or False to let it propagate.This is roughly equivalent to calling await manager.__aenter__(), running the body in a try block, and always calling await manager.__aexit__(...) afterwards. The statement is valid only inside async def functions.
For most cases a decorated async generator is shorter than a class. Code before yield is the setup, and code after it is the cleanup. Put the yield in a try and finally so cleanup runs when the body raises.
A frequent mistake is to write async with get_connection() as conn where get_connection is a plain coroutine function returning a value. That fails with 'coroutine' object does not support the asynchronous context manager protocol, because a coroutine is not itself a context manager. Return an object with __aenter__ and __aexit__, or use the decorator above.
The built-in open() blocks, so asynchronous code uses a library such as aiofiles.
Several asyncio primitives are asynchronous context managers.
asyncio.Lock, asyncio.Semaphore, asyncio.TaskGroup and asyncio.timeout() all rely on async with for correct cleanup.
Libraries such as aiohttp, httpx and async database drivers expose sessions, connections, pools and transactions as asynchronous context managers, for example async with aiohttp.ClientSession() as session: followed by async with session.get(url) as response:.
You can list several managers in one statement, and since Python 3.10 you can wrap them in parentheses:
They are entered left to right and exited in reverse order.
with calls the blocking __enter__ and __exit__ methods, while async with awaits __aenter__ and __aexit__. Use async with whenever setup or cleanup needs to await something.
Yes, for objects that are fast and do not block, such as an in-memory lock from threading that is never contended. For anything that does real I/O, prefer an asynchronous manager or run the blocking code with asyncio.to_thread().
__aexit__ is still awaited and receives the exception details. If it returns a true value the exception is suppressed; otherwise it propagates after cleanup.
No. It raises a SyntaxError outside an async def function, except in an asyncio-aware REPL such as python -m asyncio.
async with guarantees that asynchronous setup and cleanup both run, even when the body fails. Implement __aenter__ and __aexit__, or use @asynccontextmanager with a try and finally, and rely on it for sessions, locks, files, timeouts and task groups.