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 anasync with
statement. - You define an asynchronous function
run()
that holds the asynchronouswith
environment 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 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.

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.