Python itertools.tee:用 5 个可运行实验看懂分路迭代、耗尽与缓冲

10-23 5阅读

同一批数据要做两件事时,最容易写出的代码是先求和,再筛选。输入若是列表,这通常没有问题;输入若是生成器,第二次遍历却可能什么也拿不到。itertools.tee 可以给一条输入提供多个读取位置,但它没有替你解决所有重放、复制和内存问题。理解它的关键,是区分“某个分支读到了哪里”和“上游已经产出了多少”。

Python itertools.tee:用 5 个可运行实验看懂分路迭代、耗尽与缓冲
AI 模型生成的概念示意图:两条读取路径可以进度不同,暂存区用于帮助理解等待中的数据;不是实际内存结构图或软件截图。

本文包含五个完整小程序,每段都可以单独保存运行,只使用 Python 标准库。实测解释器为 CPython 3.12.14、3.13.5,两者都跑过普通模式和 -O 模式,二十次运行均与对应输出逐字节一致。每段有十条显式 require 检查,共五十个不同检查点;它们用条件判断主动抛出异常,不依赖可能在优化模式下被移除的 assert。示例只改变本地对象并打印结果,不访问网络或读写文件。

一、独立的是读取位置,不是每个元素的深复制

官方 tee 文档给出的接口是 tee(iterable, n=2):默认返回两个迭代器。下面让左分支先取两次,再让右分支取一次,观察两者是否还会得到各自应读的值。seen 只是我们放在生成器里的记录器,用来观察 yield 实际发生的顺序,不是 tee 对外公开的缓存接口。

程序后半部分故意换成一个字典元素:两个分支取得的对象具有相同身份,修改字典会被另一个引用看到。不要把“独立迭代器”理解成“递归复制所有数据”。如果业务确实需要可独立修改的嵌套对象,应另外设计复制策略;浅复制与深复制的区别可查官方 copy 文档,也要考虑复制成本。

程序一:

from itertools import tee


def require(condition, message):
    if not condition:
        raise AssertionError(message)


seen = []


def source():
    for value in (10, 20, 30):
        seen.append(value)
        yield value


left, right = tee(source())
require(seen == [], "P01: construction is lazy")
left_first = next(left)
require(left_first == 10, "P02: left starts at 10")
require(seen == [10], "P03: source yielded once")
left_second = next(left)
require(left_second == 20, "P04: left advances alone")
right_first = next(right)
require(right_first == 10, "P05: right has its own position")
require(seen == [10, 20], "P06: right reuses an available value")
right_rest = list(right)
require(right_rest == [20, 30], "P07: right gets its remaining values")
left_rest = list(left)
require(left_rest == [30], "P08: left did not move with right")

item = {"score": 1}
first, second = tee(iter([item]))
first_item = next(first)
second_item = next(second)
require(first_item is second_item, "P09: yielded object is shared")
first_item["score"] = 9
require(second_item["score"] == 9, "P10: no deep copy was made")

print("left first:", left_first, left_second)
print("right first:", right_first)
print("right rest:", right_rest)
print("left rest:", left_rest)
print("source yielded:", seen)
print("shared item:", first_item is second_item, second_item["score"])

预期输出:

left first: 10 20
right first: 10
right rest: [20, 30]
left rest: [30]
source yielded: [10, 20, 30]
shared item: True 9

左分支读完 10、20,并没有让右分支跳到 30。右分支先拿到 10,再拿到 20、30;此后左分支仍能取得自己尚未读到的 30。上游记录最终只有三个值,说明本例没有因为两个分支就重新执行两遍生成器。最后的 True 和 9 则把对象共享与读取位置独立这两件事分开验证。

二、分支也会耗尽,tee 不能恢复已经错过的数据

生成器是迭代器,不是每次遍历都会重新开始的容器。按照官方迭代器协议,一个已经结束的迭代器应继续报告结束。对现有迭代器调用 iter,也不会自动创建一次新执行;iter 的官方说明可以帮助区分“取得迭代器”和“重建数据源”。

下面先耗尽 raw,才调用 tee,两个分支自然都没有数据。后面重新创建一个生成器,再分成两路,才有完整的三个值可读。这里恢复数据的原因是新建源,而不是 tee 拥有回放历史的能力。若源在调用 tee 前已经消费了一部分,分路同样从当时的当前位置继续。

程序二:

from itertools import tee


def require(condition, message):
    if not condition:
        raise AssertionError(message)


raw = (number for number in (1, 2, 3))
first_pass = list(raw)
require(first_pass == [1, 2, 3], "E01: initial pass has data")
second_pass = list(raw)
require(second_pass == [], "E02: the generator is exhausted")
require(iter(raw) is raw, "E03: iter does not rewind an iterator")
empty_left, empty_right = tee(raw)
require(list(empty_left) == [], "E04: tee cannot restore past data")
require(list(empty_right) == [], "E05: neither branch rewinds")

left, right = tee(number for number in (1, 2, 3))
left_first = next(left)
require(left_first == 1, "E06: a fresh source begins normally")
left_rest = list(left)
require(left_rest == [2, 3], "E07: left advances to its end")
require(list(left) == [], "E08: an exhausted branch stays exhausted")
right_all = list(right)
require(right_all == [1, 2, 3], "E09: right can still read its values")
end = object()
require(next(right, end) is end, "E10: right now reaches its own end")

print("raw first:", first_pass)
print("raw second:", second_pass)
print("tee after exhaustion:", list(empty_left), list(empty_right))
print("fresh left:", [left_first] + left_rest)
print("fresh right:", right_all)
print("left again:", list(left))

预期输出:

raw first: [1, 2, 3]
raw second: []
tee after exhaustion: [] []
fresh left: [1, 2, 3]
fresh right: [1, 2, 3]
left again: []

还要留意两个分支各有自己的终点:left 已经结束时,right 仍可能有未读值;right 也读完后,两路都不能重新开始。把一个耗尽的分支再次传给普通 for 循环,既不会报错提示“忘了重建”,也不会恢复内容,所以这类问题常常表现为结果为空,而不是明显异常。

三、分路之后,不要再绕过 tee 消费原迭代器

Python 3.11 官方 tee 说明明确提醒:分路后继续使用原输入,可能在 tee 不知情时推进它。下面用完全本地、单线程的生成器复现这个风险;标着 Intentional misuse 的那一行是反例,不是推荐写法。

本例原输入 raw 本身就是一次性迭代器。不要把结论扩大成“普通列表永远不能再次读取”:为一个稳定列表另建迭代器,与直接推进 tee 所依赖的同一个原迭代器,不是同一操作。为了减少接口误用,实际代码可以直接把新建生成器交给 tee,只向后续处理步骤暴露返回的分支。

程序三:

from itertools import tee


def require(condition, message):
    if not condition:
        raise AssertionError(message)


def recorded(log):
    for value in (10, 20, 30, 40):
        log.append(value)
        yield value


seen = []
raw = recorded(seen)
left, right = tee(raw)
require(seen == [], "O01: source has not run")
left_first = next(left)
require(left_first == 10, "O02: left requests 10")
# Intentional misuse for demonstration only: do not copy this pattern.
stolen = next(raw)
require(stolen == 20, "O03: direct access bypasses tee")
right_first = next(right)
require(right_first == 10, "O04: right can still read cached 10")
left_rest = list(left)
require(left_rest == [30, 40], "O05: left never receives 20")
right_rest = list(right)
require(right_rest == [30, 40], "O06: right never receives 20")
require(seen == [10, 20, 30, 40], "O07: source did produce 20")

safe_seen = []
safe_left, safe_right = tee(recorded(safe_seen))
safe_left_all = list(safe_left)
safe_right_all = list(safe_right)
require(safe_left_all == [10, 20, 30, 40], "O08: branch-only reading is complete")
require(safe_right_all == [10, 20, 30, 40], "O09: the other branch is complete")
require(safe_seen == [10, 20, 30, 40], "O10: source ran once")

print("bypassed value:", stolen)
print("unsafe left:", [left_first] + left_rest)
print("unsafe right:", [right_first] + right_rest)
print("safe left:", safe_left_all)
print("safe right:", safe_right_all)

预期输出:

bypassed value: 20
unsafe left: [10, 30, 40]
unsafe right: [10, 30, 40]
safe left: [10, 20, 30, 40]
safe right: [10, 20, 30, 40]

20 确实由源生成了,却被直接调用 next(raw) 的代码取走。两个 tee 分支都没有得到它,因此输出都是 10、30、40。安全版本没有保留可供旁路消费的 raw,只使用 safe_left 和 safe_right,两路才都得到完整数据。这个反例说明的是源的消费权混用问题,与多线程调度没有关系。

四、快慢分支的进度差,会带来暂存需求

现在让 fast 先读四项,再让 slow 读两项。slow 读到的值必须仍然可用,即使上游已经越过它们。随后 slow 追上时,seen 没有增加,表示这些读取没有重新向源索取新值。本文把“已产出项数减去慢分支已消费项数”叫作逻辑落后量,目的只是观察消费进度。

逻辑落后量不等于已分配字节数,也不能当作精确的内部缓冲长度。它从 2 变为 0,不能推出进程立刻释放了多少内存;实现、对象大小、其他引用和分配器都会影响实际占用。记录列表 seen 自己还持有数据,因此尤其不适合拿这个教学程序做内存基准。

程序四:

from itertools import islice, tee


def require(condition, message):
    if not condition:
        raise AssertionError(message)


seen = []


def source():
    for value in range(6):
        seen.append(value)
        yield value


fast, slow = tee(source())
require(seen == [], "B01: construction did not pull values")
fast_head = list(islice(fast, 4))
require(fast_head == [0, 1, 2, 3], "B02: fast reads four values")
require(seen == [0, 1, 2, 3], "B03: four values were produced")
slow_head = list(islice(slow, 2))
require(slow_head == [0, 1], "B04: slow begins at zero")
require(seen == [0, 1, 2, 3], "B05: slow did not rerun the source")
lag_before = len(seen) - len(slow_head)
slow_catchup = list(islice(slow, 2))
require(slow_catchup == [2, 3], "B06: slow catches up from saved values")
require(seen == [0, 1, 2, 3], "B07: catching up needs no new source values")
lag_after = len(seen) - len(slow_head) - len(slow_catchup)
fast_tail = list(fast)
require(fast_tail == [4, 5], "B08: fast pulls the final values")
slow_tail = list(slow)
require(slow_tail == [4, 5], "B09: slow receives the same final values")
require(seen == list(range(6)), "B10: each value was produced once")

print("fast head:", fast_head)
print("slow head:", slow_head)
print("logical lag before catch-up:", lag_before)
print("slow catch-up:", slow_catchup)
print("logical lag after catch-up:", lag_after)
print("tails:", fast_tail, slow_tail)
print("source yielded:", seen)

预期输出:

fast head: [0, 1, 2, 3]
slow head: [0, 1]
logical lag before catch-up: 2
slow catch-up: [2, 3]
logical lag after catch-up: 0
tails: [4, 5] [4, 5]
source yielded: [0, 1, 2, 3, 4, 5]

这组输出只能证明本例的取值顺序、源的产出次数和可观察到的进度差。设计长流水线时,要问的是最慢分支会落后多久,是否可能被永久搁置。不能因为接口返回的是迭代器,就自动认为辅助存储固定不变。本文没有给出内存占用数字、吞吐量比较或压测结论,也没有通过不确定的线程竞态制造演示。

五、有限数据先后处理,list 往往更容易理解

假设只有五个数,要先求总和,再选出不小于 35 的项。tee 写法可以得到正确答案,但 sum 已经读完整条源时,筛选分支还没开始。另一种写法是先明确保存成列表,然后在同一列表上做两次计算。下面分别创建两个独立的本地源,比较结果和产出次数,不测运行时间,也不把两次源创建冒充成同一份线上数据。

Python 3.12 官方说明指出,tee 可能需要大量辅助存储,并建议在一路先消耗大部分或全部数据的情形考虑 list。这里的五项实验用于展示该消费结构,不足以证明某个实现、数据规模下的速度倍数。

程序五:

from itertools import tee


def require(condition, message):
    if not condition:
        raise AssertionError(message)


def source(log):
    for value in (10, 20, 30, 40, 50):
        log.append(value)
        yield value


tee_seen = []
for_total, for_selection = tee(source(tee_seen))
require(tee_seen == [], "T01: tee has not consumed the source")
tee_total = sum(for_total)
require(tee_total == 150, "T02: first branch computes the total")
produced_before_selection = tee_seen.copy()
require(produced_before_selection == [10, 20, 30, 40, 50], "T03: first branch is far ahead")
tee_selected = [value for value in for_selection if value >= 35]
require(tee_selected == [40, 50], "T04: second branch filters its own pass")
require(tee_seen == [10, 20, 30, 40, 50], "T05: source did not run twice")

list_seen = []
values = list(source(list_seen))
require(values == [10, 20, 30, 40, 50], "T06: list stores the finite input")
require(list_seen == values, "T07: materialization consumed the source once")
list_total = sum(values)
list_selected = [value for value in values if value >= 35]
require(list_total == tee_total, "T08: both totals agree")
require(list_selected == tee_selected, "T09: both selections agree")
require(list(values) == values, "T10: the list can be traversed again")

print("tee total:", tee_total)
print("produced before selection:", produced_before_selection)
print("tee selected:", tee_selected)
print("list total:", list_total)
print("list selected:", list_selected)
print("source counts:", len(tee_seen), len(list_seen))

预期输出:

tee total: 150
produced before selection: [10, 20, 30, 40, 50]
tee selected: [40, 50]
list total: 150
list selected: [40, 50]
source counts: 5 5

两种写法都得到总和 150 与筛选结果 40、50,两个独立源各产出五项。若数据有限、规模可控,而且本来就要先后完整遍历,列表将“保留全部输入”的选择摆在明面上。若各处理步骤确实需要独立位置、以相近节奏前进,才更值得考虑 tee。若只需几个统计量,一次循环同时更新它们也可能更直接,无须为了使用 tee 而人为分路。

落地前检查三个边界

  • 输入是否有限?不要为了让示例看起来简单,就对未知长度甚至无限的输入直接做 list;先定义处理范围和结束条件。
  • 分支会不会长期停住?为每个分支安排明确的消费责任;如果业务需要保留历史、随机访问或跨进程分发,应选择能明确表达这些需求的数据结构。
  • 是否涉及并发?官方文档明确说明 tee 迭代器不是线程安全的,同一次 tee 返回的迭代器被同时使用时可能抛出 RuntimeError。本文只演示单线程消费,不能据此推导线程安全保证。

最实用的记法是:tee 提供分开的读取位置,元素对象仍可能共享,源只向前推进,分支速度差需要付出暂存代价。先画清楚谁消费数据、先后顺序和保留期限,再决定使用 tee、列表还是单次遍历,比看到“复制迭代器”几个字就套用更稳妥。

来源核验于 2026 年 10 月 23 日。上文链接均为 Python 官方文档;文档页的当前补丁版本可能随维护更新,本文列出的实测解释器版本以实际运行结果为准。

文章版权声明:除非注明,否则均为云鹊BLOG原创文章,转载或复制请以超链接形式并注明出处。