python - Python的垃圾回收能保证在任何情况下都回收循环引用对象吗?

标签 python garbage-collection circular-reference

这个问题是我之前提出的问题的延伸:Python Delegate Pattern - How to avoid circular reference?看完回复后,我决定澄清我的问题,但被要求单独发布。

这里是:

  1. Python 文档中的一段(转载于下方)声明垃圾收集不能保证循环 引用的对象。我找到的帖子here暗示同样的事情。但对我先前问题的答复不同意。那么,我是不是误解了这段话,还是进一步 我错过了哪些细节?
  2. 我想使用弱引用,如 Alex Martelli 对问题 Should I worry about circular references in Python? 的回复中所述会完全避免他的回复中提到的垃圾收集循环引用对象的开销吗?如果是这样,它是如何工作的?

相关的 Python 文档暗示以下来自 Python 文档的段落存在冲突:

CPython implementation detail: CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the gc module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (ex: always close files).

原文可在此处找到:http://docs.python.org/reference/datamodel.html大胆的设置是我的。

提前感谢您的任何回复。

最佳答案

我认为,保证收集具有循环引用的对象的最重要原因是,根据设计,Python 从不收集具有循环引用的对象< em>如果他们定义了一个 __del__ 方法。有一个漂亮的straightforward reason :

Python doesn’t collect such cycles automatically because, in general, it isn’t possible for Python to guess a safe order in which to run the __del__() methods.

我不愿意说这是可能无法检测到具有循环引用的无法访问的对象的唯一原因。可能有一些不寻常的情况会破坏 GC 的循环检测机制。但是除非您为您的对象之一定义 __del__,否则您可能没问题。别担心,如果您发现性能问题,请使用 GC 的广泛调试选项。

关于python - Python的垃圾回收能保证在任何情况下都回收循环引用对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10629004/

相关文章:

c# - 分割 10k 页 PDF 时出现内存泄漏(iTextSharp PDF API)

c# - Windows Phone 8 上的内存泄漏

python - 为什么这段 Python 代码不会在 __hash__ 中导致死循环?

c++ - 在循环引用的上下文中处理循环包含

python - 弹出窗口中的 Kivy 按钮不调用函数

Python如何获取一个数据框中但不在第二个数据框中的值

java - 获取花在垃圾收集器上的时间

javascript - 如何在JSON.stringify : Uncaught TypeError: Converting circular structure to JSON?中找到循环结构

python - 如何在 Windows 上安装 pip3?

python - 设置 Spyder 工作区和项目的基础知识