Analysis of python coroutine concepts, analysis of python coroutine

Source: Internet
Author: User

Analysis of python coroutine concepts, analysis of python coroutine

This article describes the learning experience of the python coroutine provided by readers. The following is all about it:

The history of coroutine is long and must start with the generator.

If you have read my previous article python adventure: iterator and generator, you should be familiar with the concept of generator. The generator saves memory and generates results only when used.

 

# Generator expression a = (x * x for x in range (10) # next generate value next (a () # output 0 next (()) # output 1 next (a () # output 4

Different from the data generated by the generator, the coroutine can receive data while producing data. Specifically, yield is placed on the right of the expression. We can use. send () to send data to the coroutine function.

Def writer (): print ('-> coroutine started') for I in range (8): w = yield print (I + w) w = writer () # essence or generator >>> w <generator object writer at 0x000002595BC57468> # first use next () to activate the coroutine >>> next (w) -> coroutine started # send data >>> w. send (1) 1 # An exception will be thrown after sending to the eighth time # because the coroutine has ended the StopIteration Traceback (most recent call last)

In the first step, you must use next () to activate the coroutine function so that you can use. send () to send data in the next step.

As you can see, after receiving the data for 8th times, an exception will occur, because the program process is finished, which is normal. Add an exception. What if we need to transmit data between two coroutines?

Def writer (): while True: w = yield print ('>', w) def writer_wrapper (coro): # activate next (coro) while True: # Exception Handling try: x = yield # send data to writer coro. send (x) Cancel t StopIteration: passw = writer () wrap = writer_wrapper (w) # activate next (wrap) for I in range (4): wrap. send (I) # output> 0> 1> 2> 3

In the above Code, data is first transmitted to writer_wrapper, and then to writer.

Data --> writer_wrapper --> writer

It can be written in this way. However, it seems a little troublesome to activate it in advance and add exceptions. The emergence of yield from can solve this problem. It is also the transmission of data:

def writer():  while True:    w = yield    print('>>', w)def writer_wrapper2(coro):  yield from coro

One line of code solves the problem.

In short, yield from provides a channel for data to flow between coroutines. When yield from coro is used in writer_wrapper2, coro obtains control at this time. When we send () data, writer_wrapper2 is blocked until the writer prints the result.

At this stage, coroutine is essentially composed of generators.

Even if we use yield from to simplify the process, the knowledge of coroutines and generators is still a bit hard to understand, and yield from has many problems in asynchronous programming (asyncio used yield from before ), therefore, in python 3.5, yield from is discarded, and two new keywords async and await are added. Meanwhile, coroutine is no longer a generator type, but a native coroutine type.

Now we define a coroutine as follows:

async def func():  await 'some code'

I don't know how to use Asynchronous coroutine. So the introduction of coroutine is over. Thank you for your support.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.