Python __aexit__ Method
Last modified November 17, 2026 Python 3.15
The __aexit__ method closes an asynchronous context. It is the
counterpart of __aenter__: async with awaits it after
the body, passing information about any exception that escaped. The return
value of __aexit__ decides whether that exception is suppressed or
propagated. This article shows the method's signature, cleanup patterns, and the
rules for commit, rollback, and exception handling.
Signature and return value
The method receives self and three exception arguments:
exc_type, exc_value, and traceback.
When the block finishes normally, all three are None. Returning a
false value, or None, lets an exception propagate; returning a true
value suppresses it. The method must return an awaitable;
async def is the usual way to provide one, and
async with awaits its result.
import asyncio
class Context:
async def __aenter__(self):
print("enter")
return self
async def __aexit__(self, exc_type, exc, tb):
print(f"exit: {exc_type.__name__ if exc_type else None}")
return False
async def main():
async with Context():
print("body")
try:
async with Context():
raise ValueError("boom")
except ValueError as e:
print(f"caught: {e}")
asyncio.run(main())
The first block has no exception, so __aexit__ receives
None and returns False; the program continues. The
second block raises ValueError, and the same return value lets the
exception reach the surrounding try statement. The type name is
printed as ValueError in the exit line.
$ python basic_aexit.py enter body exit: None enter exit: ValueError caught: boom
Suppressing an exception
Returning True tells async with that the exception
has been handled and should not propagate. Suppression should be selective:
check the exception type and return False for everything else.
Otherwise a context manager can silently hide bugs.
import asyncio
class SuppressValueError:
async def __aenter__(self):
print("enter")
return self
async def __aexit__(self, exc_type, exc, tb):
if exc_type is ValueError:
print(f"suppressing: {exc}")
return True
return False
async def main():
async with SuppressValueError():
raise ValueError("ignored")
print("after the first block")
try:
async with SuppressValueError():
raise KeyError("not ignored")
except KeyError as e:
print(f"caught: {e}")
asyncio.run(main())
The first block raises ValueError, which the manager suppresses,
so the next line runs normally. The second block raises KeyError;
the manager returns False, and the surrounding try
catches it. The return value can be any truthy object, but returning a real
boolean is clearer.
$ python suppress.py enter suppressing: ignored after the first block enter caught: 'not ignored'
Inspecting exception details
The three arguments give the exception class, the exception instance, and its traceback. They can be used for logging, metrics, or deciding whether to suppress. The innermost frame of the traceback identifies where the exception was raised, which is often more useful than a generic message.
import asyncio
class LoggingContext:
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
if exc_type is None:
print("no exception")
else:
print(f"type: {exc_type.__name__}")
print(f"message: {exc}")
print(f"raised in: {tb.tb_frame.f_code.co_name}")
return False
async def main():
async with LoggingContext():
print("clean block")
try:
async with LoggingContext():
raise ValueError("bad value")
except ValueError:
pass
asyncio.run(main())
The clean block produces no exception. The failing block passes
ValueError, the message bad value, and a traceback
whose innermost frame is main, the function containing the
raise. The method returns False, so the exception is
still handled by the outer try.
$ python exception_details.py clean block no exception type: ValueError message: bad value raised in: main
Commit or roll back
A transaction is a natural use of __aexit__: commit when the body
succeeds and roll back when it raises. The method should not reraise the
exception it received; returning False is enough to let the
caller handle it.
import asyncio
class Transaction:
def __init__(self, store):
self.store = store
self.pending = []
async def __aenter__(self):
print("begin")
return self
async def __aexit__(self, exc_type, exc, tb):
await asyncio.sleep(0.05)
if exc_type is None:
self.store.extend(self.pending)
print(f"commit: {self.store}")
else:
print(f"rollback: discarded {self.pending}")
return False
def add(self, item):
self.pending.append(item)
async def main():
store = []
async with Transaction(store) as tx:
tx.add("alice")
tx.add("bob")
try:
async with Transaction(store) as tx:
tx.add("carol")
raise RuntimeError("disk full")
except RuntimeError as e:
print(f"caught: {e}")
print(f"final store: {store}")
asyncio.run(main())
The first transaction adds two items and commits them to the store. The second
raises RuntimeError, so its pending items are discarded and the
exception propagates. The final store contains only the committed items. A real
database transaction would wrap the same pattern around
commit() and rollback() calls.
$ python transaction.py begin commit: ['alice', 'bob'] begin rollback: discarded ['carol'] caught: disk full final store: ['alice', 'bob']
Timing a block
__aexit__ runs on every exit path, which makes it suitable for
measurement, logging, and cleanup that must happen even when the body fails.
The following timer reports the duration of an asynchronous operation.
import asyncio
import time
class Timer:
async def __aenter__(self):
self.start = time.perf_counter()
return self
async def __aexit__(self, exc_type, exc, tb):
elapsed = time.perf_counter() - self.start
print(f"elapsed: {elapsed:.1f}s")
return False
async def work():
await asyncio.sleep(0.2)
async def main():
async with Timer():
await work()
asyncio.run(main())
The elapsed time includes the await asyncio.sleep(0.2) inside the
block. The exact value depends on the system and the event loop, so the output
below is only one possible run. If the body raised, the timer would still run
and would return False to let the exception continue.
$ python timer.py elapsed: 0.2s
Best practices
Cleanup code is easy to get wrong because it runs in exceptional situations.
These rules keep __aexit__ reliable:
- Release every resource acquired by
__aenter__, including on the exception path. - Return
FalseorNoneby default; suppress only the specific exception types you can actually handle. - Do not reraise the exception passed to
__aexit__; return a false value instead. - If cleanup itself raises, that new exception replaces the original one and
the original becomes its
__context__; keep cleanup simple and handle its own errors. - Remember that cancellation is delivered as
CancelledError, so cleanup should account for it;asyncio.shieldcan protect a critical cleanup coroutine, but it does not make the surrounding task uncancellable. Avoid blocking calls in the method. - Remember that
__aexit__also runs forreturn,break, andcontinuethat leave the block.
Source
object.__aexit__ - Python documentation
Asynchronous context managers - Python documentation
async with - Python documentation
contextlib.asynccontextmanager - Python documentation
In this article we have implemented the __aexit__ method. We have
covered its three exception arguments, suppressing selected exceptions,
inspecting tracebacks, committing or rolling back a transaction, timing a
block, and the rules for reliable asynchronous cleanup. For related topics, see
Python __aenter__ method,
Python __exit__ method,
Python __enter__ method,
Python context managers,
Python asyncio, and
Python async await.
Author
List all Python tutorials.