gpt4 book ai didi

python-3.x - python3.6,async with和await的区别

转载 作者:行者123 更新时间:2023-12-03 16:55:01 24 4
gpt4 key购买 nike

来自 python 3.4 的新手开发人员在这里。

我幼稚的理解是只使用关键字async with当我看到协程是上下文管理器时?

最佳答案

来自 PEP 492 :

A new statement for asynchronous context managers is proposed:

async with EXPR as VAR:
BLOCK

which is semantically equivalent to:

mgr = (EXPR)
aexit = type(mgr).__aexit__
aenter = type(mgr).__aenter__(mgr)

VAR = await aenter
try:
BLOCK
except:
if not await aexit(mgr, *sys.exc_info()):
raise
else:
await aexit(mgr, None, None, None)


所以是的——它会生成从 __aenter__ 返回的协程。给定上下文管理器的方法,一旦返回就运行你的 block ,然后进入 __aexit__协程。

关于python-3.x - python3.6,async with和await的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48362738/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com