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')
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!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处理