Skip to content Skip to sidebar Skip to footer

Python Asynchronous Context Manager

In Python Lan Ref. 3.4.4, it is said that __aenter__() and __aexit__() must return awaitables. However, in the example async context manager, these two methods return None: class A

Solution 1:

The methods in this example do not return None. They are async functions, which automatically return (awaitable) asynchronous coroutines. This is similar to how generator functions return generator iterators, even though they usually have no return statement.

Solution 2:

Your __aenter__ method must return a context.

classMyAsyncContextManager:
    asyncdef__aenter__(self):
        await log('entering context')
        # maybe some setup (e.g. await self.setup())return self

    asyncdef__aexit__(self, exc_type, exc, tb):
        # maybe closing context (e.g. await self.close())await log('exiting context')

    asyncdefdo_something(self):
        await log('doing something')

usage:

asyncwithMyAsyncContextManager() as context:
    await context.do_something()

Post a Comment for "Python Asynchronous Context Manager"