为什么我不能从异步函数内部“产生"?

编程入门 行业动态 更新时间:2024-10-28 08:26:45
本文介绍了为什么我不能从异步函数内部“产生"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在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

Asynchronous yield from

虽然在理论上可以实现对以下内容的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".

更多推荐

为什么我不能从异步函数内部“产生"?

本文发布于:2023-11-15 19:54:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1597478.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!