“收益来自"是什么意思?asyncio 中的语法 do 以及它与“await"有何不同? [英] What does the "yield from" syntax do in asyncio and how is it different from "await"

查看:26
本文介绍了“收益来自"是什么意思?asyncio 中的语法 do 以及它与“await"有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从写过 asyncio 代码但希望更好地了解内部工作原理的人的角度来看,什么是 yield fromawait 以及这些对允许有什么用异步代码?

From the perspective of someone who has written asyncio code but is looking to better understand the inner workings, what is yield from, await and how are those useful for allowing asynchronous code?

有一个 高度赞成 询问yield from 语法和解释 async 和 await,但两者都深入探讨了不同的主题,并不是对底层代码及其如何与 asyncio 配合的简明解释.

There is one highly upvoted question asking about the uses of the yield from syntax and one explaining async and await, but both go in depth about different topics and are not really a concise explanation of the underlying code and how it fits in with asyncio.

推荐答案

简短回答:

yield from 是等待 asyncio 协程的旧方法.

yield from is an old way to wait for asyncio's coroutine.

await 是一种现代的等待 asyncio 协程的方式.

await is a modern way to wait for asyncio's coroutine.

详细回答:

Python 有生成器——一种特殊的函数,它产生一系列结果而不是单个值.从 Python 3.3 开始,添加了 yield from 表达式.它允许一个生成器将其部分操作委托给另一个生成器.

Python has generators - special kind of functions that produces a sequence of results instead of a single value. Starting with Python 3.3 yield from expression was added. It allows one generator to delegate part of its operations to another generator.

从 Python 3.4 开始 asyncio 模块已添加到标准库中.它使我们能够编写清晰易懂的异步代码.虽然技术上 asyncio 的协程可以通过不同的方式实现,但在 asyncio 中,它们是使用生成器实现的(您可以观看 优秀视频,展示了如何使用生成器来实现协程).@asyncio.coroutine 是一种从生成器生成协程的方法,yield from 是一种等待协程的方法 - 只是实现的细节.

Starting with Python 3.4 asyncio module was added to standard library. It allow us to write clear and understandable asynchronous code. While technically asyncio's coroutines could be implemented different ways, in asyncio they were implemented using generators (you can watch for excellent video where shown how generators can be used to implement coroutines). @asyncio.coroutine was a way to make coroutine from generator and yield from was a way to await for coroutine - just details of implementation.

这就是 yield from 开始用于两个不同的东西"的原因.

That's how happened that yield from started to be used for two "different things".

从 Python 3.5 开始(参见 PEP 492)协程有了新的语法.现在您可以使用 async def 定义协程,并使用 await 表达式等待它.它不仅写得更短,而且更清楚地了解我们使用 asyncio 的协程.

Starting with Python 3.5 (see PEP 492) coroutines got new syntax. Now you can define coroutine with async def and await for it using await expression. It's not only shorter to write, but also makes clearer to understand that we work with asyncio's coroutines.

如果您使用的是 Python 3.5+,您可以忘记对 asyncio 的协程使用 yield from 并使用 await 来实现它.

If you're using Python 3.5+ you can forget about using yield from for asyncio's coroutines and use await for it.

这篇关于“收益来自"是什么意思?asyncio 中的语法 do 以及它与“await"有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆