本文介绍了为什么我不能从异步函数内部“产生"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

在Python 3.6中,我可以在协程内部使用yield.但是我不能使用yield from.

In Python 3.6, I am able to use yield inside a coroutine. However I am not able to use yield from.

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

Below is my code. On line 3 I await another coroutine. On line 4 I try to yield from a file. Why won't Python 3.6 allow me to do that?

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为上述代码引发的异常:

Here's the exception Python 3.6 raises for the above code:

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

推荐答案

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

According to PEP 525, which introduces asyncronous generators in Python 3.6:

虽然在理论上可以实现对以下内容的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对于异步生成器也不太重要,因为 无需提供实现另一种机制的机制 协程之上的协程协议.并组成异步 生成器可以使用一个简单的async for循环:

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

如您所见,答案归结为实施起来太困难了,反正您也不需要它."

As you can see, the answer boils down to "it would be too hard to implement, and you don't need it anyway".

这篇关于为什么我不能从异步函数内部“产生"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:44