python asynchronous context manager

后端 未结 2 497
灰色年华
灰色年华 2021-01-20 11:33

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

2条回答
  •  孤城傲影
    2021-01-20 11:50

    Your __aenter__ method must return a context.

    class MyAsyncContextManager:
        async def __aenter__(self):
            await log('entering context')
            # maybe some setup (e.g. await self.setup())
            return self
    
        async def __aexit__(self, exc_type, exc, tb):
            # maybe closing context (e.g. await self.close())
            await log('exiting context')
    
        async def do_something(self):
            await log('doing something')
    

    usage:

    async with MyAsyncContextManager() as context:
        await context.do_something()
    

提交回复
热议问题