Python coroutine and python coroutine
If Python books have a certain guiding role, the (coroutine is) Documentation lacks the least-known Python features, so it seems to be the most useless feature on the surface.
-- David Beazley
Python author
The dictionary uses the verb "to yield" to provide two definitions: Output and concession. For yield in the Python generator, both meanings are true. The yield item line of code will generate a value and provide it to next (...) in addition, the caller will make concessions to pause the execution generator so that the caller can continue to work until another value is required to call next (). The caller pulls the value from the generator.
Syntactically, coroutine is similar to generator, and is a function that defines the body containing the yield keyword. However, in the coroutine, yield usually appears on the right side of the expression (for example, datum = yield), which can produce a value or no output-if there is no expression after the yield keyword, the generator generates None. The coroutine may receive data from the caller, but the caller provides the data to the coroutine using the. send (datum) method instead of the next (...) function. Generally, the caller pushes the value to the coroutine.
The yield keyword even does not receive or transmit data. Regardless of how data flows, yield is a process control tool that enables collaborative Multitasking: The coroutine can give the Controller to the central scheduler to activate other coroutines.
FundamentallyYield is a way to control the processIn this way, you can understand the coroutine.
How the generator evolves into a coroutine
The underlying architecture of coroutine is defined in "PEP 342-Coroutines via EnhancedGenerators" (https://www.python.org/dev/peps/pep-0342/) and implemented in Python 2.5 (2006. Since then, the yield keyword can be used in the expression, and The. send (value) method is added to the generator API. The caller of the generator can use. Send (...)Method to send data. The sent data becomes the value of the yield Expression in the generator function. Therefore, the generator can be used as a coroutine. A coroutine is a process that works with the caller to generate the value provided by the caller.
Except. send (...) method, PEP 342 is added. throw (...) and. close () method: the former is used to let the caller throw an exception and process it in the generator. The latter is used to terminate the generator.
Basic Behavior of the generator used as the coroutine
For example