Python-generator yield-coroutine

tags: yield  Builder

1. The difference between iterator and generator:

  1. The generator is a special iterator, so the usage of the iterator can be used in the generator
  2. To define an iterator, you need to implement the __iter__() method and the __next__() method separately.
  3. To define a generator, only one yield is needed

2. The concept of coroutine

  1. A coroutine is not a process or thread, and its execution is more similar to a subroutine, or a function call without a return value.
  2. A program can contain multiple coroutines, and can compare multiple threads with one process, so let's compare coroutines and threads. We know that multiple threads are relatively independent, have their own context, and the switch is controlled by the system; the coroutine is relatively independent and has its own context, but its switching is controlled by itself, and the current coroutine switches to other coroutines from the current coroutine. To control.
  3. From the above literal understanding, multi-threaded pause and start is controlled by the operating system, such as gil. The coroutine is single-threaded. In a single thread, there is a function to pause, start, and pass values ​​to the function. We call it a coroutine.
  4. In Python, the generator yield has exactly this pause and start function. We can think about using generators as a coroutine.

3. Builder

WithyieldFunction, is a special iterator, containsGenerator functionwithGenerator expression(as an expression of (elem for elem in [1, 2, 3]))

Generator example:

# 
 # Input: 1. 5-->5 2. 3 --->8 3. 2--->10 4. 2---->12
 # Output: 1. 5 2. 4 3. 3.333 4. 3
def avg():
    num = 0
    total = 0.0
         # 
    while 1:
                 # 
        val = yield
                 #Calculation +1
        num += 1
        total += val
                 #  is equal to the total / calculation times
        avg = total/num
                 Print('current average{}'.format(avg))

counter = avg()
counter.send(None)
while True:
         Num = input('Please enter a number:')
    num = float(num)
    counter.send(num)

Code interpretation

  • The right side of yield indicates that a value is generated, but in fact, the left side of yield can indicate the value passed by the caller, but we generally don't write it, so it will pass None by default.
  • Call the next method to start the generator. After startup, the generator pauses on the first yield and generates a value that is the value to the right of the yield expression.
  • Call the send method, the left side of the yield will accept the value, and execute downwards. If there is no yield pause, the stopItertion exception will be thrown out.
  • The generator can pause, and accept values, and features with coroutines exist.

View the status of the generator:

from inspect import getgeneratorstate
def simple_gen1():
    print('started')
    x = yield 'running'
    print('receive_x:',x)
    y = yield x
    print('receive_y:', y)
    
test1 = simple_gen1()
    print(getgeneratorstate(test1))
    next(test1)
print(getgeneratorstate(test1))
next(test1)
print(getgeneratorstate(test1))
try:
    next(test1)
except Exception:
    pass
print(getgeneratorstate(test1))

##output:
    GEN_CREATED
started
GEN_SUSPENDED
receive_x: None
GEN_SUSPENDED
receive_y: None
GEN_CLOSED

From the above code, we can see that the generator is stateful -> not activated, paused, has ended

Intelligent Recommendation

Yield in python coroutine

The coroutine is a lightweight thread that implements task switching in a single thread. His scheduling does not require a 'stunning' operating system, and the switching overhead between tasks is smal...

Python - coroutine - yield

Coroutine Coroutine, also known as micro-threading, fiber. English name Coroutine. The coroutine is Coroutine is another implementation in pythonMultitaskingThe way it is just smaller than the thread ...

Python yield keyword and coroutine

Generator generator Before discussing the coroutine, let's take a look at python.Builder. In simple terms, in Python, the mechanism of computing while looping is calledBuilder. for example. Generating...

Python: yield coroutine

Coroutine Coroutines, also known as micro-threads, coroutines are lightweight threads A user state (operating system simply does not know of his existence, is the user's own control) is a coroutine fu...

More Recommendation

The yield in Python coroutine

Coroutine, also called micro-threads, shred. English Coroutine. Subroutine or function is called, is a call hierarchy in all languages, such as A calls B, B in the implementation process and called C,...

Python coroutine yield from

The difference between generator and coroutine The usage of yield in Python is very similar to return, both of which provide a return value, but the biggest difference between yield and return is that...

30. python-coroutine-yield

Iterator Iteration is a way to access collection elements. An iterator is an object that can remember the position of traversal. The iterator object is accessed from the first element of the collectio...

Realize python coroutine with yield

Just introduced the pythonyield keyword, strike while the iron is hot, now let's learn about the yield implementation of the coroutine. To quote the official statement: γ€€γ€€ Compared with threads, corou...

Understanding of Python yield coroutine

yield Such as: Because yield can suspend the execution of the function, it can also re-execute the particularity of the function, which can realize the coroutine First get all the functions, that is, ...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top