On the yield mechanism in Python

Source: Internet
Author: User
Tags generator

Looking at the part about the Liaoche in Python recently, I saw some confusion about the consumer and producer part of the official website, so I researched it and had the following understanding:
Code:

DEF consumer ():
    r = ' A ' while
    True:
        print (' there ')
        n = yield r
        Print ("Here")
        if not n:
            return
        print (' [CONSUMER] consuming%s ... '% n)
        r = ' OK '


def Produce (c):
    c.send (None)
    n = 0
  while N < 5:
        n = n + 1
        print (' [PRODUCER] producing%s ... '% n)
        r = C.send (n)
        print (' [PRODUCER] Co Nsumer return:%s '% R '
    c.close ()

First we initialize a consumer:
c = Consumer ()

Note: Since consumer () contains yield, then consumer () automatically becomes an iterator generator, so first we start this iterator:
C.send (None)

Note: The Send (None) here is equivalent to next (), but you cannot start the iterator via Send (1), passing in the argument:

C.send (1)
Typeerror:can ' t send non-none value to a just-started generator

Next look at the first case:

c = Consumer ()
c.send (None)

#输出
there

#说明: After initializing the iterator, terminating
n = yield r after executing the yield statement

So what would be the value of printing c.send (None) in a different way?

Print (C.send (none))

#输出
there
a

#说明: Initializes an iterator, C.send (none) automatically returns the value of yield r, which is the value of the current iterator iteration R, because the first assignment R is ' a ', So the value of the current iterator iteration to R is ' a '.

Next continue:

c = Consumer ()
c.send (None)
print (C.send (1))

#输出
there
here
[consumer] consuming 1 ...
There
OK

#说明:
1. After initializing the iterator, and then invoking the iterator through C.send (1), the code continues from where the last iteration stopped, that is, n = yield R. In other words, initializing an iterator means that the iterator sets the start point to the statement in which yield R is located, and that each time the iterator is invoked, it starts here.

2.N = yield R This means that when an iterator is invoked, assigns the value r of the current iteration to N, and C.send (1) Returns the value of R, because R is the variable that the iterator iterates over, and we execute r= ' OK ' at the end of the loop, then C.send (1) The return is OK.

3. Why does it output there? That's because of the while loop, which is an infinite loop, unless you call C.send (None) again to terminate the iterator iteration to throw the stopiteration, or call C.close (), or it will loop and go back to the statement yield R is in. Wait for the next call iteration.

Go on: (If you can guess what the results will be output, congratulations) you have mastered the yield operating mechanism. )

c = Consumer ()
c.send (None)
print (C.send (c.send (1))

#输出
there here
[consumer] consuming 1. There here
[CONSUMER] consuming OK ...
There
OK

Master the use of yield, so now speak consumer and produce together to see:

c = consumer ()
Produce (c)

#输出
there
[PRODUCER] producing 1 ...
Here
[CONSUMER] consuming 1 ...
There
[PRODUCER] Consumer return:200 OK
[PRODUCER] producing 2 ...
Here
[CONSUMER] consuming 2 ...
There
[PRODUCER] Consumer return:200 OK
[PRODUCER] producing 3 ...
Here
[CONSUMER] consuming 3 ...
There
[PRODUCER] Consumer return:200 OK
[PRODUCER] producing 4 ...
Here
[CONSUMER] consuming 4 ...
There
[PRODUCER] Consumer return:200 OK
[PRODUCER] producing 5 ...
Here
[CONSUMER] consuming 5 ...
There
[PRODUCER] Consumer return:200 OK

Summarize:
The reason why the yield is implemented is because when produce calls C.send (n), it can trigger the consumer to execute its own process, wait for consumer to return after execution, produce continue execution, and finally end the process according to the judgment.
Compared with the traditional producer consumer scheme, there is no lock, single thread, shared resource, no worry about deadlock, and more efficient in the whole process.

If you have any comments, please leave a message ~

Related Article

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.