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

Why can't I 'yield from' inside an async function?

在 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

如您所见,答案归结为 "it would be too hard to implement, and you don't need it anyway"。