python asynchronous context manager

隐身守侯 提交于 2019-12-24 00:59:28

问题


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 AsyncContextManager:
    async def __aenter__(self):
        await log('entering context')

    async def __aexit__(self, exc_type, exc, tb):
        await log('exiting context')

Is this code correct?


回答1:


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()



回答2:


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.



来源:https://stackoverflow.com/questions/48390977/python-asynchronous-context-manager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!