在 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 simpleasync 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/