python3.6、async with和await的区别

python3.6, difference between async with and await

来自 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__ 方法返回的协程,一旦它 returns 运行你的块,然后进入 __aexit__ 协程.