Python __aexit__() Magic Method

Rate this post
object.__aexit__(self, exc_type, exc_val, exc_tb)

πŸ’‘ Summary: Python’s __aexit__() magic method is semantically similar to __exit__() but is used for asynchronous and parallel programming. Python calls the __aexit__() magic method when leaving an async with block whereas the __aenter__() method is called when entering 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.