python异步上下文管理器

python异步上下文管理器,python,asynchronous,contextmanager,Python,Asynchronous,Contextmanager,在Python Lan参考3.4.4中,据说和必须返回可等待项。但是,在示例异步上下文管理器中,这两个方法不返回任何值: class AsyncContextManager: async def __aenter__(self): await log('entering context') async def __aexit__(self, exc_type, exc, tb): await log('exiting context') 此代码

在Python Lan参考3.4.4中,据说
必须返回可等待项。但是,在示例异步上下文管理器中,这两个方法不返回任何值:

class AsyncContextManager:
    async def __aenter__(self):
        await log('entering context')

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

此代码正确吗?

此示例中的方法不返回
None
。它们是
async
函数,自动返回(等待的)异步协同路由。这类似于生成器函数返回生成器迭代器的方式,即使它们通常没有
return
语句。

您的
\uuuu aenter\uuu
方法必须返回上下文

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')
用法:

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

事实并非如此
\uuu aenter\uuu
允许
返回
某些内容,但它不必返回。并非所有上下文管理器(异步或非异步)都需要该功能。(另外,如果它返回某个内容,则该内容不必是“上下文”。)