实现说明
events 定义在模块顶层,中间不经过函数作用域。
使用要点
- 演示输出是带标签的(
historian:、auditor:、parent remaining:),每个操作都会留下自己的一行标注。
常见问题
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 全部导入都来自标准库:itertools。 文件的状态由几个模块级绑定持有:events。
代码示例
from itertools import tee
events = iter(["boot", "login", "deploy", "logout"])
# tee splits one single-pass iterator into independent cursors.
historian, auditor = tee(events)
# Branch 1 pulls the first two events off its own cursor...
print("historian:", [next(historian) for _ in range(2)])
# ...while branch 2 still yields the full stream: tee buffers items
# one branch reads until the other catches up.
print("auditor:", list(auditor))
# tee itself exhausts the source iterator; drive the branches, not the parent.
print("parent remaining:", list(events))
# Drain order does not matter: whatever one branch read is buffered for the other.
a, b = tee([1, 2, 3, 4, 5])
print("b fully drained:", list(b))
print("a still intact:", list(a))