让发电机长时间运行有危险吗



我正在设计运行某些枚举模拟的代码。我将把代码放在最后,但我不认为我的问题真的应该涉及这个程序的细节。原则上,我认为我的问题同样适用于这个更简单的示例脚本:

class Generator:
def __init__(self, n):
self.current = 0
self.limit = n
self.end_reached = False
def next(self):
if self.current == self.limit:
self.end_reached = True
if self.end_reached:
return None
# Here the point is to have an example where 
# the variable could potentially store a very large 
# object.  Will Python's garbage collection, or whatever,
# wisely use space, or could this be dangerous for 
# the computer's memory?
out = [i for i in range(self.limit)]
self.current += 1
return out
example = Generator(a_really_big_number)
count = 0
while not example.end_reached:
count += 1
example.next()

如果我输入一个非常大的n并让它运行一整天,它会损坏我的电脑吗?我需要手动插入某种中断吗?还是编译器会帮我做?特别是因为我正在构建的实际应用程序,几乎是通过设计,体验到了";组合爆炸";我经常会面临一个听起来无害的输入导致大量计算的风险,所以我一直在考虑是否也需要构建一个";发电机转轮";在一些迭代、内存事件或类似事件后自动插入中断,以确保我的计算机安全。


我想这是无关紧要的,但我在Windows 10计算机上运行,使用VSCode IPythonNotebooks。Python 3.8.13。


这是我正在构建的实际生成器,以防查看实际应用程序有用。

class CProd_Generator:
'''Generator for the Cartesian product of a list of sets (but sets are represented as lists).'''
def __init__(self, setList):
if len(setList) == 0:
raise Exception("Empty setList on construction")
self.setList = setList
self.current_index = [0 for i in range(len(setList))]
self.max_index = [len(setList[i])-1 for i in range(len(setList))]
self.end_reached = False
def step(self, property):
'''Get next element to be generated, if it satisfies the property.'''
sl = self.setList
ci = self.current_index
mi = self.max_index
n = len(sl)
out = tuple([sl[i][ci[i]] for i in range(n)])
i = 0
while ci[i] == mi[i]:
ci[i] = 0
if (i:=i+1) == n:
self.end_reached = True
break
if i < n:
ci[i] += 1
if property(out):
return out
return None

def next(self, property=lambda x: True):
while not self.end_reached:
if (out := self.step(property)) != None:
return out
return None

def reset(self): 
self.current_index = [0 for i in range(len(self.setList))]
self.end_reached = False

outnext()方法中的局部变量。当方法返回时,变量将消失。

如果调用者没有保存所有返回的值,它们将被垃圾回收。

生成器中没有保存所有返回值的内容。例如,您不会将它们保存在实例变量中。

最新更新