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 @   ascertain  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2020-09-19 MessagePack:python
2020-09-19 json:python
2020-09-19 CSV:python
2020-09-19 Python: pickle
2020-09-19 .ini文件的python处理
点击右上角即可分享
微信分享提示