Python: yield from

 

import time


def dubious():
    print(f"\033[32;40;7m{'dubious start'}\033[0m")
    while True:
        send_value = yield
        if send_value is None:
            break
        commence = time.time()
        time.sleep(send_value)

    print('in dubious', time.time() - commence)
    # print('in dubious')
    return time.time() - commence
    # return 'return from dubious'


def grouper():
    while True:
        yield_from_value = yield from dubious()
        print('in grouper', yield_from_value)


g = grouper()
print('{0} {1} {0}'.format('~' * 20, 1))
print('next1 =', next(g))
print('{0} {1} {0}'.format('~' * 20, 2))
print('next2 =', g.send(2))
print('{0} {1} {0}'.format('~' * 20, 3))
print('next3 =', g.send(None))
print('{0} {1} {0}'.format('~' * 20, 4))
print('next4 =', g.send(None))

 

 

 

# grouper 死循环,每一次循环都会生成一个新的dubious generator,不断从dubious generator取值,最后捕获StopIteration,把dubious generator的StopIteration的异常 exc.value赋值给yield_from_value
# 此时,grouper的第一轮循环结束,再次进入while True循环,进行相同过程


import types, typing, time


def gen():
    yield 11
    yield 22
    # raise TypeError
    return '44'


g = gen()


def f(it: typing.Iterator):
    while True:
        v = yield from it  # 当it不能yield值后,yield无法让出执行权
        print('v =', v)
        time.sleep(1)


t = f(g)

while True:
    print('>> ', next(t))
    time.sleep(2)
    print('sleep two seconds in global while')

 

 

 

 

posted @ 2022-09-19 16:11  ascertain  阅读(30)  评论(0)    收藏  举报