简体   繁体   中英

coroutines in python using yield

I am trying to understand coroutines in python with yield operator.

def minimize():
    current = yield
    while True:
        value = yield current
        current = min(value, current)

I have the function minimize() which returns the minimum value of the all the values that has been sent to the function till that point.

it = minimize()
next(it)        
print(it.send(10))
print(it.send(4))
print(it.send(22))
print(it.send(-1))

>>>
10
4
4
-1

I have a question regarding the function.

what does current = yeild achieve. From what I understood of yield in a generator context, yeild returns the next value when you use next() on the generator object.

Let's follow the flow control, indented items are the minimize() generator:

it = minimize()   # Creates generator
next(it)
    current = yield       # suspends on yield (implicit None)
print(it.send(10))
    current = 10          # resumes
    while True:
        value = yield 10  # suspends on yield
# Output: 10
print(it.send(4))
        value = 4         # resumes
        current = min(4, 10)
    while True:
        current = yield 4
# Output: 4
print(it.send(22))
        value = 22
        current = min(22, 4)
    while True:
        current = yield 4
# Output: 4
print(it.send(-1))
        value = -1
        current = min(-1, 4)
    while True:
        current = yield -1
# Output: -1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM