python3.6,async with和await的区别

lay*_*cat 9 python-3.x python-asyncio python-3.6

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

我的天真理解只是async with在看到协程是上下文管理器时才使用关键字?

小智 12

来自PEP 492:

提出了异步上下文管理器的新声明:

async with EXPR as VAR:
    BLOCK
Run Code Online (Sandbox Code Playgroud)

这在语义上等同于:

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)
Run Code Online (Sandbox Code Playgroud)

所以是的 - 它产生到从__aenter__给定上下文管理器的方法返回的协程中,一旦它返回就运行你的块,然后产生到__aexit__协程中。