Python __aenter__() Magic Method

Rate this post
object.__aenter__(self)

💡 Summary: Python’s __aenter__() magic method is semantically identical to __enter__() but is used for asynchronous and parallel programming. Python calls the __aenter__() magic method when starting an async with block whereas the __aexit__() method is called when leaving it. An object that implements both __aenter__() and __aexit__() methods is called an asynchronous context manager.

import asyncio


class MyAsyncContextManager:

    async def __aenter__(self):
        print("ENTER async with")

    async def __aexit__(self, *args):
        print("EXIT async with")


async def run():
    async with MyAsyncContextManager() as cm:
        print("BODY async with")


asyncio.get_event_loop().run_until_complete(run())

Output:

ENTER async with
BODY async with
EXIT async with
  • We define a custom class MyAsyncContextManager that defines the __aenter__() and __aexit__() magic methods to make it an asynchronous context manager, i.e., allowing it to be used in an async with statement.
  • You define an asynchronous function run() that holds the asynchronous with environment and run it using the asyncio.get_event_loop().run_until_complete() function. The reason for this is that you need to use the async with block within an asynchronous function (using the expression async def to define it).

We call this a “Dunder Method” for Double Underscore Method” (also called “magic method”). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.