Sobes.tech
Junior — Middle

How to implement an asynchronous context manager for resource management in asynchronous programs?

sobes.tech AI

Answer from AI

In Python, the asynchronous context manager protocol with methods __aenter__ and __aexit__ is used to implement an asynchronous context manager. This allows managing resources in asynchronous code, such as opening and closing connections or files.

Example of an asynchronous context manager:

class AsyncResource:
    async def __aenter__(self):
        print("Opening resource")
        # Initialize resource, e.g., open a connection
        return self

    async def __aexit__(self, exc_type, exc, tb):
        print("Closing resource")
        # Release resource, e.g., close a connection


import asyncio

async def main():
    async with AsyncResource() as resource:
        print("Using resource")

asyncio.run(main())

This approach guarantees that the resource will be properly released even if exceptions occur inside the async with block.