asynchronous context manager

In Python, an asynchronous context manager is an object that creates a context that allows you to allocate resources before running asynchronous code and release them after. To use this type of context manager, you need the async with statement.

Asynchronous context managers are particularly useful when you need to run setup and teardown logic reliably, even if your asynchronous code encounters an error or interruption.

To create an asynchronous context manager, you define a class that implements two special method:

  1. .__aenter__() is called when entering the context.
  2. .__aexit__() is called when leaving the context.

These methods allow you to define asynchronous setup and teardown logic for the asynchronous context.

Example

Here’s a quick example of an asynchronous context manager:

Python
>>> class AsyncContextManager:
...     async def __aenter__(self):
...         print("Entering context: Setup logic here...")
...         return self
...     async def __aexit__(self, exc_type, exc_val, exc_tb):
...         print("Exiting context: Teardown logic here...")
...

>>> async def main():
...     async with AsyncContextManager():
...         print("Inside context: Your async code here...")
...

>>> import asyncio
>>> asyncio.run(main())
Entering context: Setup logic here...
Inside context: Your async code here...
Exiting context: Teardown logic here...

This example demonstrates the order of execution for the .__aenter__() and .__aexit__() methods when using an asynchronous context manager.

Tutorial

Async IO in Python: A Complete Walkthrough

This tutorial will give you a firm grasp of Python’s approach to async IO, which is a concurrent programming design that has received dedicated support in Python, evolving rapidly from Python 3.4 through 3.7 (and probably beyond).

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated April 7, 2025 • Reviewed by Leodanis Pozo Ramos