垃圾收集在关闭一段时间后不会删除无法访问的对象

Dmi*_*rba 7 python garbage-collection

我有以下假设的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()
Run Code Online (Sandbox Code Playgroud)

程序打印0,这对我来说很奇怪,因为:

  • 首次分配时,将str创建对象并引用该对象a.
  • 在第二次赋值时,将str创建第二个对象a,现在由其引用a.
  • 但是,第一个str对象从未被删除,因为我们已经关闭了自动垃圾收集,因此它仍然存在于内存中.
  • 因为它确实存在于内存中,但是无法访问,这看起来就像垃圾收集应该删除的那种对象.

我非常感谢为什么没有收集它的解释.

PS我知道Python会将一些对象(包括-3到100之间的整数,就我记忆而言)视为单例,但这些特定字符串无法成为这样的对象.

PPS我将它作为一个整体程序运行,而不是在shell中运行

Ned*_*der 7

Python中的gc模块仅负责收集循环结构.当引用计数变为0时,会立即回收像字符串这样的简单对象.gc不报告简单对象,禁用它不会阻止字符串被回收.

额外的高级细节:即使gc模块负责所有对象回收,第一个字符串仍然不会在gc.collect()调用时收集,因为仍然存在对该字符串的实时引用:co_consts脚本代码对象的元组中的引用.