gpt4 book ai didi

python - 在Python中,如何卸载生成的类

转载 作者:行者123 更新时间:2023-12-01 06:19:49 25 4
gpt4 key购买 nike

我正在开发一个将文件(hfd5 - pytables)加载到对象结构中的库。用于该结构的实际类作为字符串从 hdf5 文件加载,然后以这种方式加载:

class NamespaceHolder(dict):
# stmt is the source code holding all the class defs
def execute(self, stmt):
exec stmt in self

问题是,像这样加载多个类会导致对象出现在垃圾回收的不可回收部分,即实际的类定义中。我也可以将其加载到全局字典中,但问题仍然是孤立类。有没有办法卸载类?

主要问题是 class.mro 属性,它包含返回到类本身的引用,导致垃圾收集器无法处理的循环引用。

这是一个小测试用例,您可以自行查看:

import gc

if __name__ == "__main__":
gc.enable()
gc.set_debug(gc.DEBUG_LEAK)

code = """
class DummyA(object):
pass
"""
context = {}

exec code in context
exec code in context

gc.collect()
print len(gc.garbage)

请注意:我已经反对使用解析文件中的文本来创建类,但显然他们打算在这里使用它并看到一些我没有看到的好处,所以放弃这个解决方案并不是'现在可行。

最佳答案

gc.set_debug(gc.DEBUG_LEAK) 导致泄漏。试试这个:

import gc

def foo():
code = """
class DummyA(object):
pass
"""
context = {}
exec code in context
exec code in context

gc.collect()
print len(gc.garbage), len(gc.get_objects())

gc.enable()
foo(); foo() # amount of objects doesn't increase
gc.set_debug(gc.DEBUG_LEAK)
foo() # leaks

关于python - 在Python中,如何卸载生成的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/919924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com