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:
β₯οΈ Info: Are you AI curious but you still have to create real impactful projects? Join our official AI builder club on Skool (only $5): SHIP! - One Project Per Month
ENTER async with BODY async with EXIT async with
- We define a custom class
MyAsyncContextManagerthat defines the__aenter__()and__aexit__()magic methods to make it an asynchronous context manager, i.e., allowing it to be used in anasync withstatement. - You define an asynchronous function
run()that holds the asynchronouswithenvironment and run it using theasyncio.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 expressionasync defto 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.