“收益"是什么?语法在asyncio中执行,它与"await"有何不同? [英] What does the "yield from" syntax do in asyncio and how is it different from "await"
问题描述
从编写异步代码但希望更好地了解内部工作原理的人的角度来看,yield from
,await
是什么,以及这些对于允许异步代码有用吗?
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?
有一个解释异步和等待的内容,但是两者都深入探讨了不同的主题,并且实际上不是对基础代码及其与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+,则可以忘记将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中执行,它与"await"有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!