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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With