为什么我不能从'异步函数内'中获益?

时间:2017-11-19 11:40:53

标签: 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

1 个答案:

答案 0 :(得分:14)

根据PEP 525,它介绍了Python 3.6中的异步生成器:

  

异步yield from

     

虽然理论上可以实现yield from支持   异步生成器,它需要严肃的重新设计   发电机实施。

     对于异步生成器,

yield from也不那么重要了   没有必要提供实施另一种机制   协同程序顶部的协程协议。并组成异步   生成器可以使用简单的async for循环:

async def g1():
    yield 1
    yield 2

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

正如你所看到的,答案归结为"它实施起来太难了,而你无论如何都不需要它#34;。

相关问题