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

标签 python-3.x python-3.6 python-asyncio

来自 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/

相关文章:

python - 使用 python 创建分层数据。基于结果列表

python-3.x - 协程的 Python 回溯

python - Python 3.6 中的格式化字符串文字是什么?

python - `asyncio.wait([asyncio.sleep(5)])` 和 `asyncio.sleep(5)` 之间的区别

python - 如何编写一致的有状态上下文管理器?

python - 循环内可调用变量的限制

python - 解析 XML 时出现标签不匹配错误?

python - pyspark:仅基于 rdd 的操作

python - 当通过命令行执行时,导入日期时间会在 Python 脚本中引发 ModuleNotFound 'math'

python - 如何在 Python Pandas 中将日期转换为季度而不重复前 5 年的季度?