Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python 3.5, is the keyword "await" equivalent to "yield from"?

In the document here: https://docs.python.org/3/library/asyncio-task.html, I found many yield from can be replaced by await.

I was wondering whether they are equivalent all the time in Python 3.5. Does anyone have ideas about this?

like image 687
Hanfei Sun Avatar asked May 15 '17 22:05

Hanfei Sun


People also ask

What is the difference between the await keyword and the yield keyword?

A generator function is executed yield by yield i.e one yield-expression at a time by its iterator (the next method) whereas async-await, they are executed sequential await by await. Async/await makes it easier to implement a particular use case of Generators.

Is await same as yield from Python?

yield from is an old way to wait for asyncio's coroutine. await is a modern way to wait for asyncio's coroutine. Detailed answer: Python has generators - special kind of functions that produces a sequence of results instead of a single value.

What does the await keyword do in Python?

The keyword await passes function control back to the event loop. (It suspends the execution of the surrounding coroutine.) If Python encounters an await f() expression in the scope of g() , this is how await tells the event loop, “Suspend execution of g() until whatever I'm waiting on—the result of f() —is returned.

Does await always yield?

If its target yield s, await "passes on" the suspension to its own caller. This allows to suspend an entire stack of coroutines that all await each other. If its target returns s, await catches the return value and provides it to its own coroutine.


1 Answers

No, they are not equivalent. await in an async function and yield from in a generator are very similar and share most of their implementation, but depending on your Python version, trying to use yield or yield from inside an async function will either cause an outright SyntaxError or make your function an asynchronous generator function.

When the asyncio docs say "await or yield from", they mean that async functions should use await and generator-based coroutines should use yield from.

like image 177
user2357112 supports Monica Avatar answered Oct 04 '22 23:10

user2357112 supports Monica