python - 为什么我不能在异步函数中使用 'yield from'?

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

在 Python 3.6 中,我可以在协同程序中使用 yield。但是我无法使用 yield from

下面是我的代码。在第 3 行,我等待另一个协程。在第 4 行,我尝试 yield from 一个文件。为什么 Python 3.6 不允许我这样做?

async def read_file(self, filename):
    with tempfile.NamedTemporaryFile(mode='r', delete=True, dir='/tmp', prefix='sftp') as tmp_file:
        await self.copy_file(filename, tmp_file)
        yield from open(tmp_file)

这是 Python 3.6 为上述代码引发的异常:

  File "example.py", line 4
    yield from open(tmp_file)
    ^
SyntaxError: 'yield from' inside async function

最佳答案

根据 PEP 525 ,它在 Python 3.6 中引入了异步生成器:

Asynchronous yield from

While it is theoretically possible to implement yield from support for asynchronous generators, it would require a serious redesign of the generators implementation.

yield from is also less critical for asynchronous generators, since there is no need provide a mechanism of implementing another coroutines protocol on top of coroutines. And to compose asynchronous generators a simple async for loop can be used:

async def g1():
    yield 1
    yield 2

async def g2():
    async for v in g1():
        yield v

如您所见,答案归结为“实现起来太难了,而且您也不需要它”。

关于python - 为什么我不能在异步函数中使用 'yield from'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47376408/

相关文章:

javascript - 导出异步等待变量并在 JS 中完成 "awaiting"后将其导入另一个文件

c# - 依赖注入(inject)的 UserManager 正在处理异步调用 (ASP.NET CORE)

javascript - 无法从另一个文件返回数据React Native

Python Selenium - 无法点击按钮

python - 如何为作为服务运行的 Python 脚本提供输入

python - 如何组织和分发带有 C 扩展的 Python 应用程序?

python - 如何使用 Django choicefield 动态设置选项?

python-3.x - Python3 写入文件 beautifulsoup

Python subprocess.Popen 通过管道进行通信

python - 在 Pandas Dataframe 上执行 SQL 并将结果存储在同一 Dataframe 中