Sobes.tech
Junior — Middle

Can you list and explain the magic methods used in asynchronous context managers?

sobes.tech AI

Answer from AI

In Python, asynchronous context managers use two magic methods:

  • __aenter__(self) — called when entering the asynchronous context (async with). It should return an awaitable object, usually the manager itself or a resource.
  • __aexit__(self, exc_type, exc, tb) — called when exiting the context, also returns an awaitable. It allows handling exceptions within the context.

Example of a simple asynchronous context manager:

class AsyncManager:
    async def __aenter__(self):
        print('Entering context')
        return self

    async def __aexit__(self, exc_type, exc, tb):
        print('Exiting context')
        if exc:
            print(f'Handling exception: {exc}')

import asyncio

async def main():
    async with AsyncManager() as manager:
        print('Inside context')

asyncio.run(main())

Thus, these methods allow managing resources in asynchronous code, ensuring proper opening and closing.