我有以下假设的Python程序,它使用了一些垃圾收集器函数(文档):
import gc
# Should turn automatic garbage collection off
gc.disable()
# Create the string
a = "Awesome string number 1"
# Make the previously assigned string unreachable
# (as an immutable object, will be replaced, not edited)
a = "Let's replace it by another string"
# According to the docs, collect the garbage and returns the
# number of objects collected
print gc.collect()
该程序打印0
,这对我来说似乎很奇怪,因为:
- 首次分配时,将创建
str
对象并由a
引用。 - 在第二次赋值时,将创建并
a
第二个str
对象,现在由a
引用。 - 但是,第一个
str
对象从未被删除,因为我们已经关闭了自动垃圾回收,因此它仍然存在于内存中。 - 由于它确实存在于内存中,但无法访问,因此这似乎正是垃圾回收应该删除的对象类型。
我将非常感谢为什么不收集它的原因。
附言我确实知道 Python 将某些对象(据我所知,包括从 -3 到 100 的整数)视为单例,但这些特定的字符串不可能是这样的对象。
P.P.S 我正在将其作为一个整体程序运行,而不是在外壳中运行
Python 中的 gc 模块只负责收集循环结构。 字符串等简单对象在其引用计数变为 0 时会立即回收。 GC 不会报告简单对象,禁用它不会阻止回收字符串。
额外的高级细节:即使 gc 模块负责所有对象回收,第一个字符串仍然不会在gc.collect()
调用时收集,因为仍然有一个对该字符串的实时引用:脚本代码对象的co_consts
元组中的引用。