itertools.tee 个生成器的隐式内存消耗

implicit memory consumption with itertools.tee of generators

我正在使用 here and here 的答案来检查我的生成器 x 是否为空。

from itertools import tee
def my_generator():
    yield from range(100000000)
x = my_generator()
x, y = tee(x)
try:
    next(y)
except StopIteration:
    # x is empty do something
    quit()

x中提取的元素会发生什么变化?它们可以 丢弃 吗?或者必须保存在内存中 y?

# now consume x entirely
for z in x:
    print(x)
# how can y iterate over its objects ?
# will they have to reside in memory now ??

tl;dr - 从 x 产生的元素将保存在内存中,直到它们也从 y 产生。

使用 itertools.tee 时,必须为从 tee 返回的所有迭代器保存所有生成元素的副本。 在您的情况下,它们是 xy.

这样做是为了允许通过 xy 进行完全迭代。

如果您查看 Python docs for itertools.tee 中的等效实现,您会看到所有生成的值都被保存,直到它们从返回的所有生成器 tee 中生成。

在您的情况下,您必须同时使用 xy 或让它们(两者)超出范围并进行垃圾收集以释放项目。