Summary of usage of python yield and yield from

Posted by Angerslave on Sun, 04 Aug 2019 09:41:27 +0200

Links to the original text: https://www.jianshu.com/u/8f2987e2f9fb

Example 1. The first N numbers of Fibonacci sequence with simple output
Disadvantage: The reusability of this function is poor, because the fab function returns None, other functions can not get the sequence generated by this function.
To improve the reusability of fab functions, it is better to return a List instead of printing out a sequence directly.

'''
Nobody answered the question? Editor created a Python learning and communication QQ group: 857662006 
Look for like-minded friends, help each other, there are good video learning tutorials and PDF e-books in the group!
'''
def fab1(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b,end=' ')
        a, b = b, a + b
        n = n + 1
fab1(5)  

** Example 2. **
Disadvantage: The memory occupied by the function in operation will increase with the increase of parameter max, if we want to control the memory occupancy,
It's better not to use List to save intermediate results, but to iterate through iterable objects

def fab2(max): 
    n, a, b = 0, 0, 1 
    L = [] 
    while n < max: 
        L.append(b) 
        a, b = b, a + b 
        n = n + 1 
    return L

** Example 3 **
Note: A function with yield is no longer a normal function, and the Python interpreter treats it as a generator.
Calling fab(5) does not execute the fab function, but returns an iterable object!
When the for loop executes, each loop executes the code inside the fab function. When yield b is executed, the fab function returns an iteration value.
In the next iteration, the code continues to execute from the next statement of yield b, and the local variables of the function look exactly the same as before the last interruption.
The function then continues to execute until it encounters yield again.

'''
//Nobody answered the question? Editor created a Python learning and communication QQ group: 857662006 
//Look for like-minded friends, help each other, there are good video learning tutorials and PDF e-books in the group!
'''
def fab3(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        # print b
        a, b = b, a + b
        n = n + 1
f=fab3(5)
print("f It's an iterative object, and it doesn't execute functions.")
print(f)
print('fab3 The return is a iterable Objects that can be used for Loop acquisition value')
for n in f:
    print(n)

Case 4:
Note: yield from iterable is essentially the abbreviation for item in iterable: yield item

'''
//Nobody answered the question? Editor created a Python learning and communication QQ group: 857662006 
//Look for like-minded friends, help each other, there are good video learning tutorials and PDF e-books in the group!
'''
def f_wrapper1(f):
   for g  in f:
       yield g
wrap = f_wrapper1(fab3(5))
for i in wrap:
   print(i,end=' ')

print('\n Use yield from replace for loop')
def f_wrapper2(f):
    yield from f#Note that this must be a generatable object
wrap = f_wrapper2(fab3(5))
for i in wrap:
   print(i,end=' ')
print('\n---------------------')


print('yield from Contains multiple subroutines')
def g(x):
   yield from range(x, 0, -1)
   yield from range(x)
print(list(g(5)))
for g  in g(6):
   print(g,end=',')
    
    
print('\n---------------------')  Notice that the red part is the replacement part. yield from iterable Essentially equal to for item in iterable: yield item The abbreviated version of ____________  

Example 5 uses yield from statement to transmit data to generator
The traditional producer-consumer model is that a thread writes messages, a thread cancels messages, and controls queues and waiting through lock mechanism, but it may be deadlocked if it is not careful.
# If the process is changed, the producer will jump to the consumer directly through yield after the production message. When the consumer has finished the execution, the producer will continue to produce. The efficiency is very high.

'''
//Nobody answered the question? Editor created a Python learning and communication QQ group: 857662006 
//Look for like-minded friends, help each other, there are good video learning tutorials and PDF e-books in the group!
'''
def  consumer_work(len):
    # Read send incoming data and simulate data processing
    print("writer:")
    w=''
    while True:
        w = yield w    # w receives send incoming data as well as returned data
        print('[CONSUMER] Consuming %s...>> ', w)
        w*=len #Multiply the returned data by 100
        time.sleep(0.1) 
def consumer(coro):
    yield from coro#Pass data to the coroutine (generator) object
 
 
def produce(c):
    c.send(None)# "prime" the coroutine
    for i in range(5):
        print('[Produce] Producing %s----', i)
        w=c.send(i)#After sending is completed, it enters the process of execution.
        print('[Produce] receive %s----', w)
    c.close()
     
c1=consumer_work(100)
produce(consumer(c1))<br><br>Implementation results:<br>writer:<br>[Produce] Producing %s---- 0<br>[CONSUMER] Consuming %s...>>  0<br>[Produce] receive %s---- 0<br>[Produce] Producing %s---- 1<br>[CONSUMER] Consuming %s...>>  1<br>[Produce] receive %s---- 100<br>[Produce] Producing %s---- 2<br>[CONSUMER] Consuming %s...>>  2<br>[Produce] receive %s---- 200<br>[Produce] Producing %s---- 3<br>[CONSUMER] Consuming %s...>>  3<br>[Produce] receive %s---- 300<br>[Produce] Producing %s---- 4<br>[CONSUMER] Consuming %s...>>  4<br>[Produce] receive %s---- 400<br><br>yield from Generally mastering these two usages is enough.

Topics: Python