What does the "exit from" syntax do in asyncio and how does it differ from "wait",

From the point of view of the person who wrote the asynchronous code, but who wants to better understand the internal workings, what is yield from , await and how are they useful for resolving asynchronous code?

There is one issue with increased attention to how to use the yield from syntax and the one explaining async and expecting , but both go deeper on different topics and are not really a brief explanation of the underlying code and how it fits into asyncio.

+7
python generator coroutine async-await python-asyncio
source share
1 answer

Short answer:

yield from is an old way of waiting for a coroutine.

await is a modern way of waiting for a coroutine.

Detailed response:

Python has generators - special types of functions that produce a sequence of results instead of a single value. Starting with the Python 3.3 yield from . It allows one generator to delegate part of its operations to another generator.

Starting with the Python 3.4 module, asyncio been added to the standard library. This allows us to write clear and understandable asynchronous code. Although technically asynchronous coroutines can be implemented in different ways, in asyncio they were implemented using generators (you can watch a great video showing how generators can be used to implement coroutines). @asyncio.coroutine was a way to make a coroutine from a generator, and yield from is a way to wait for coroutine - just implementation details.

What happened is that yield from began to be used for two "different things".

Starting with Python 3.5 (see PEP 492 ). coroutines got a new syntax. Now you can define the coroutine with async def and wait for it with the await expression. This is not only shorter, but it is also clear that we work with coroutines.

If you are using Python 3.5+, you may forget to use yield from for anything other than generators, and use await for coroutines.

+8
source share

All Articles