ZetCode

Python __aenter__ Method

Last modified November 17, 2026 Python 3.15

The async with statement uses two special methods: __aenter__ prepares a resource and __aexit__ releases it. Both are asynchronous, so setup and cleanup can perform real I/O without blocking the event loop. This article focuses on __aenter__: what it must return, how its result reaches the as target, and what happens when entering the context fails.

The async with protocol

When Python evaluates async with manager as value, it calls manager.__aenter__() and awaits the result. That result is assigned to value, the body runs, and manager.__aexit__(...) is awaited on the way out. __aenter__ is usually defined with async def; more generally, it must return an awaitable.

basic_aenter.py
import asyncio


class AsyncResource:
    async def __aenter__(self):
        print("acquiring resource")
        await asyncio.sleep(0.1)
        return self

    async def __aexit__(self, exc_type, exc, tb):
        print("releasing resource")
        await asyncio.sleep(0.1)


async def main():
    async with AsyncResource() as resource:
        print(f"using {type(resource).__name__}")


asyncio.run(main())

The program prints acquiring resource before the body and releasing resource after it. Both methods are coroutines, and async with awaits each one. The as target is the object returned by __aenter__, which in this example is self.

$ python basic_aenter.py
acquiring resource
using AsyncResource
releasing resource

Returning a different object

__aenter__ does not have to return the context manager itself. It can return a prepared connection, a response, or any other object that the body should use. This keeps the manager's own state private and gives the body only the resource it needs.

return_value.py
import asyncio


class Response:
    def __init__(self, status, body):
        self.status = status
        self.body = body


class HttpSession:
    async def __aenter__(self):
        print("opening session")
        await asyncio.sleep(0.05)
        return Response(200, "hello")

    async def __aexit__(self, exc_type, exc, tb):
        print("closing session")
        await asyncio.sleep(0.05)


async def main():
    async with HttpSession() as response:
        print(response.status, response.body)


asyncio.run(main())

The HttpSession object manages the session, but the body receives a Response with status and body attributes. The session is still closed by __aexit__ when the block ends. Returning a useful object from __aenter__ is often cleaner than forcing the body to call a separate open() method.

$ python return_value.py
opening session
200 hello
closing session

Acquiring a pooled connection

A context manager can also wrap a shared pool. The pool itself stays alive between blocks, while a small helper object implements the two asynchronous methods for one checkout. The following example uses a list as a simplified pool of connection objects.

connection_pool.py
import asyncio


class Connection:
    def __init__(self, name):
        self.name = name


class Pool:
    def __init__(self):
        self.free = [Connection("conn-1"), Connection("conn-2")]

    def connection(self):
        return PooledConnection(self)


class PooledConnection:
    def __init__(self, pool):
        self.pool = pool
        self.connection = None

    async def __aenter__(self):
        await asyncio.sleep(0.05)
        self.connection = self.pool.free.pop()
        print(f"checked out {self.connection.name}")
        return self.connection

    async def __aexit__(self, exc_type, exc, tb):
        await asyncio.sleep(0.05)
        self.pool.free.append(self.connection)
        print(f"returned {self.connection.name}")


async def main():
    pool = Pool()

    async with pool.connection() as connection:
        print(f"querying with {connection.name}")

    print(f"free connections: {[c.name for c in pool.free]}")


asyncio.run(main())

pool.connection() creates a fresh PooledConnection for each async with statement. __aenter__ removes a connection from the free list and returns it, so the body works with the connection rather than with the wrapper. __aexit__ puts it back; the free list is restored after the block.

$ python connection_pool.py
checked out conn-2
querying with conn-2
returned conn-2
free connections: ['conn-1', 'conn-2']

When __aenter__ fails

If __aenter__ raises an exception, the body never runs and __aexit__ is not called. This is the same rule as for the synchronous with statement. If the method acquired something before the failure, it must undo that partial work itself.

enter_failure.py
import asyncio


class BrokenConnection:
    async def __aenter__(self):
        print("connecting")
        raise ConnectionError("server unreachable")

    async def __aexit__(self, exc_type, exc, tb):
        print("cleanup")  # never runs


async def main():
    try:
        async with BrokenConnection():
            print("inside")
    except ConnectionError as e:
        print(type(e).__name__, e)


asyncio.run(main())

The only line from the manager is connecting; the cleanup line never appears because the failure happens before the body. The exception is caught and printed by the outer handler. A real implementation should release a partially acquired connection inside __aenter__ before reraising, or acquire the resource in a way that either succeeds completely or leaves no state behind.

$ python enter_failure.py
connecting
ConnectionError server unreachable

Using contextlib.asynccontextmanager

For simple cases, contextlib.asynccontextmanager builds both methods from one async generator. The code before yield is the enter step, the yielded value becomes the as target, and the code after yield is the exit step. A try/finally around the yield guarantees cleanup if the body fails.

async_contextmanager.py
import asyncio
from contextlib import asynccontextmanager


@asynccontextmanager
async def open_cache(name):
    print(f"open {name}")
    await asyncio.sleep(0.05)
    try:
        yield name.upper()
    finally:
        await asyncio.sleep(0.05)
        print(f"close {name}")


async def main():
    async with open_cache("users") as cache:
        print(f"using {cache}")


asyncio.run(main())

This version is shorter than a class with two methods and is a good default when the setup and cleanup fit in one generator. The finally block runs whether the body completes normally or raises. Use a class when you need reusable state, multiple entry points, or more control over the exception information.

$ python async_contextmanager.py
open users
using USERS
close users

Best practices

An asynchronous context manager should make acquisition and release obvious and should not hide failures:

Source

object.__aenter__ - Python documentation

Asynchronous context managers - Python documentation

async with - Python documentation

contextlib.asynccontextmanager - Python documentation

In this article we have used the __aenter__ method to prepare asynchronous resources. We have covered the async with protocol, returning a value other than self, connection pooling, failure during entry, and the asynccontextmanager helper. For related topics, see Python __aexit__ method, Python __enter__ method, Python __exit__ method, Python context managers, Python asyncio, and Python async await.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.