python异步上下文管理器 [英] python asynchronous context manager

查看:151
本文介绍了python异步上下文管理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python Lan参考中3.4.4,据说__aenter__()__aexit__()必须返回等待项.但是,在示例异步上下文管理器中,这两个方法返回None:

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

此代码正确吗?

推荐答案

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

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.

这篇关于python异步上下文管理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆