Python itertools.product:输出惰性,输入为何会先耗尽?

10-23 6阅读

做参数网格时,itertools.product 很容易被理解成“所有东西都等到需要时才计算”。真正需要分开的是输入与输出:组合逐个产生,但输入值要先收集成池。官方文档明确要求有限输入。对于正常的正重复次数,少取几个结果并不能省掉这一步,也不能让无限数据源变得安全。

Python itertools.product:输出惰性,输入为何会先耗尽?
模型生成的概念示意图,非软件截图;托盘表示输入池,传送带表示逐个输出。

下面五个程序均可单独运行,只使用标准库。已在 CPython 3.12.14、3.13.5 的普通和 -O 模式下测试,均启用 -I -S -B;共三十七项显式检查,二十次运行的标准输出完全一致。检查失败会主动抛出异常,不依赖会被优化模式移除的断言语句。

一、按输入顺序推进,不替你排序

可以把各输入看作不同轴:最右轴先走完,再推动左侧轴。这里故意给出逆序值,证明函数保留输入顺序,并不执行排序。重复次数重复的是整组轴;只有一个输入时,才直观地表现为自身配对。重复值也不会自动去重。结果对象只能向前读取,读完不会重新开始。

from itertools import product

checks = 0

def check(actual, expected, label):
    global checks
    if actual != expected:
        raise RuntimeError(f"{label}: {actual!r} != {expected!r}")
    checks += 1

p = product((2, 1), ("b", "a"))
check(iter(p) is p, True, "iterator returns itself")
first = next(p)
check(first, (2, "b"), "first tuple follows input order")
rest = list(p)
check(rest, [(2, "a"), (1, "b"), (1, "a")], "rightmost axis moves fastest")
check(next(p, "END"), "END", "exhausted iterator stays exhausted")
square = list(product("AB", repeat=2))
check(square, [("A", "A"), ("A", "B"), ("B", "A"), ("B", "B")], "repeat one pool")
check(list(product("AB", [1], repeat=2)),
      [("A", 1, "A", 1), ("A", 1, "B", 1),
       ("B", 1, "A", 1), ("B", 1, "B", 1)], "repeat the whole axis sequence")
check(list(product("AA", "x")), [("A", "x"), ("A", "x")], "duplicates are retained")
print("order:", [first] + rest)
print("repeat:", square)
print("checks:", checks)

预期标准输出:

order: [(2, 'b'), (2, 'a'), (1, 'b'), (1, 'a')]
repeat: [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]
checks: 7

二、构造已经触发读取

记录器先创建生成器,随后才调用组合函数。打印发生在第一次取结果之前,却已经出现全部读取记录,说明构造阶段就建立了池。之后推进结果,输入记录不再增加。这对带有读文件、查询或计费副作用的数据源尤其重要:即使后面很快退出循环,前面的工作也已经发生。

这里的读取时点、从左到右建池,以及遇到空轴后仍读取后续轴,属于本次两版 CPython 的实测行为。对应的三点十二固定版本源码和三点十三固定版本源码都在构造函数中逐个收集输入。不要把这些副作用细节当成所有解释器永久不变的协议。

from itertools import product

checks = 0

def check(actual, expected, label):
    global checks
    if actual != expected:
        raise RuntimeError(f"{label}: {actual!r} != {expected!r}")
    checks += 1

events = []

def tapped(name, size):
    for value in range(size):
        events.append(f"{name}{value}")
        yield value

left, right = tapped("L", 3), tapped("R", 2)
check(events, [], "creating generators does not run their bodies")
p = product(left, right)
check(events, ["L0", "L1", "L2", "R0", "R1"], "CPython pools at construction")
print("after construction:", events)
first = next(p)
check(first, (0, 0), "first result")
check(events, ["L0", "L1", "L2", "R0", "R1"], "next uses stored pools")
check(list(p), [(0, 1), (1, 0), (1, 1), (2, 0), (2, 1)], "remaining output")
events.clear()
empty = product([], tapped("T", 2))
check(events, ["T0", "T1"], "CPython still pools after an empty axis")
check(list(empty), [], "empty axis makes empty product")
print("after empty axis:", events)
print("checks:", checks)

预期标准输出:

after construction: ['L0', 'L1', 'L2', 'R0', 'R1']
after empty axis: ['T0', 'T1']
checks: 7

三、没有轴与存在空轴不同

没有输入轴时,有一种“什么都不选”的选择,因此得到一个空元组;有轴但其中没有候选项时,则根本无法组成结果。重复次数为零会移除全部轴,也得到一个空元组,负数会被拒绝。

还要留意一个实现边界:本次实测中,零次重复没有消费生成器。固定源码对这个分支有专门处理。文档中的近似实现有助于理解结果,却不保证副作用时点完全相同。不要依靠零次重复来触发输入校验、清理或其他业务动作。

from itertools import product

checks = 0

def check(actual, expected, label):
    global checks
    if actual != expected:
        raise RuntimeError(f"{label}: {actual!r} != {expected!r}")
    checks += 1

check(list(product()), [()], "zero axes give one empty tuple")
check(list(product([], [1])), [], "empty first axis")
check(list(product([1], [])), [], "empty final axis")
check(list(product([], repeat=0)), [()], "zero repetitions remove an empty axis")
check(list(product("AB", repeat=0)), [()], "zero repetitions remove a nonempty axis")
error = None
try:
    product("AB", repeat=-1)
except ValueError as exc:
    error = type(exc).__name__
check(error, "ValueError", "negative repeat is rejected")
seen = []

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

p = product(source(), repeat=0)
check((list(p), seen), ([()], []), "CPython repeat zero skips input consumption")
print("zero axes:", list(product()))
print("negative repeat:", error)
print("repeat=0 input visits:", seen)
print("checks:", checks)

预期标准输出:

zero axes: [()]
negative repeat: ValueError
repeat=0 input visits: []
checks: 7

四、同一个迭代器,不能当作两份输入

把同一个一次性迭代器作为两个参数传入,第一次建池会耗尽它,第二个池便为空。使用重复参数时则先收集一次,再复用池;二者对一次性来源并不等价。需要真正独立的轴,可以分别创建生成器,或者先明确缓存成可重复遍历的序列,再传给不同位置。

池也不是深拷贝快照。下面替换外层列表元素并追加项目,不改变已经选入池的成员;修改原字典,却会影响尚未取出和已经返回的结果。结果元组不可变,不代表其中的对象不可变。官方复制文档解释了引用与递归复制的区别;若业务需要值快照,应按对象结构自行选择复制策略,别默认所有对象都适合深拷贝。

from itertools import product

checks = 0

def check(actual, expected, label):
    global checks
    if actual != expected:
        raise RuntimeError(f"{label}: {actual!r} != {expected!r}")
    checks += 1

g = (letter for letter in "AB")
check(list(product(g, g)), [], "second argument sees the same exhausted iterator")
check(next(g, "END"), "END", "the shared iterator was consumed")
g = (letter for letter in "AB")
square = list(product(g, repeat=2))
check(square, [("A", "A"), ("A", "B"), ("B", "A"), ("B", "B")], "repeat reuses the collected pool")
check(next(g, "END"), "END", "repeat consumed its input")
box = {"value": 1}
source = [box]
p = product(source, [0, 1])
source[0] = {"value": 99}
source.append({"value": 100})
box["value"] = 2
rows = list(p)
check(len(rows), 2, "outer replacement and append do not change pooled membership")
check(all(row[0] is box for row in rows), True, "results share the original object")
check([row[0]["value"] for row in rows], [2, 2], "mutation before output is visible")
box["value"] = 3
check([row[0]["value"] for row in rows], [3, 3], "mutation after output is also visible")
print("repeat:", square)
print("shared values:", [row[0]["value"] for row in rows])
print("checks:", checks)

预期标准输出:

repeat: [('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]
shared values: [3, 3]
checks: 8

五、限制输出,不等于限制输入

外层 islice 只拿一个结果,六项输入仍全部被读取;即使要求零个输出,构造也早已完成。原因既包括前面的建池行为,也包括函数调用的求值顺序:必须先得到内层调用的返回值,才能把它交给外层。外层限额无法追回已经发生的工作。

将截取放到某个输入上,才限制该池接收的项目数量;其他轴也需要分别设定边界。不过这会改变组合范围,并不是完整笛卡尔积的等价优化。程序只使用小型有限生成器,不实际构造无限输入。真正的无限输入无法正常完成建池,可能持续占用时间和内存。

from itertools import islice, product

checks = 0

def check(actual, expected, label):
    global checks
    if actual != expected:
        raise RuntimeError(f"{label}: {actual!r} != {expected!r}")
    checks += 1

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

outer_seen = []
outer = list(islice(product(source(6, outer_seen), "xy"), 1))
check(outer, [(0, "x")], "outer islice limits results")
check(outer_seen, [0, 1, 2, 3, 4, 5], "outer islice does not limit constructor pooling")
inner_seen = []
g = source(6, inner_seen)
inner = list(product(islice(g, 2), "xy"))
check(inner_seen, [0, 1], "inner islice limits this input pool")
check(inner, [(0, "x"), (0, "y"), (1, "x"), (1, "y")], "bounded input changes the domain")
check(next(g), 2, "remaining source can still be read")
check(inner_seen, [0, 1, 2], "source resumes at its next item")
zero_seen = []
zero = list(islice(product(source(3, zero_seen), "xy"), 0))
check(zero, [], "zero results requested")
check(zero_seen, [0, 1, 2], "zero results still require constructor pooling")
print("outer limit:", outer, "input visits:", outer_seen)
print("inner limit:", inner)
print("zero output input visits:", zero_seen)
print("checks:", checks)

预期标准输出:

outer limit: [(0, 'x')] input visits: [0, 1, 2, 3, 4, 5]
inner limit: [(0, 'x'), (0, 'y'), (1, 'x'), (1, 'y')]
zero output input visits: [0, 1, 2]
checks: 8

使用前的三道检查

先确认每个来源有限且读取成本可接受,再确认它能否重复遍历,最后确认元素是否允许共享修改。即使所有输入都很小,组合总数仍会随轴数迅速增长:三个各有十项的轴就产生一千个结果。生产代码尽量逐个处理,测试中转成列表只是为了核对小样本,不能据此推断大规模组合也适合全部留在内存。

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