C API/GC: datetime.datetime doesn't have `Py_TPFLAGS_HAVE_GC`, potentially causing leaks in `tzinfo` cycles
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- PR 合并指标
- PR 指标待抓取
描述
Bug report
Bug description:
The GC docs say (emphasis mine)
Python’s support for detecting and collecting garbage which involves circular references requires support from object types which are “containers” for other objects which may also be containers. Types which do not store references to other objects, or which only store references to atomic types (such as numbers or strings), do not need to provide any explicit support for garbage collection.
However in datetime, PyDateTime_DateTimeType is a container (of tzinfo), but doesn’t have the GC flags set.
With help on Python's discuss forums, I was able to get to this minimal example that appears to show a possible leak.
from datetime import datetime, tzinfo
import gc, sys
class MyTzinfo(tzinfo): pass
tz = MyTzinfo()
dt = datetime(2000, 1, 1, tzinfo=tz)
tz.foo = dt # circular ref introduced here
assert sys.getrefcount(tz) == 3 # 1 from dt, 1 variable, 1extra from passing it in
assert sys.getrefcount(tz) == 3 # 1 from tz, 1 variable, 1extra from passing it in
assert len([obj for obj in gc.get_objects() if isinstance(obj, MyTzinfo)]) == 1
del tz
assert len([obj for obj in gc.get_objects() if isinstance(obj, MyTzinfo)]) == 1
del dt
gc.collect()
# At this point, dt and tz should be gone
assert len([obj for obj in gc.get_objects() if isinstance(obj, MyTzinfo)]) == 0
If datetime is replaced with a dummy class, the above program works:
class datetime:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
I'm happy to submit a PR if needed.
CPython versions tested on:
3.12
Operating systems tested on:
macOS
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从 Modules/_datetimemodule.c 开始,检查 PyDateTime_DateTimeType,以及它的 tzinfo 引用如何与垃圾回收支持交互。运行最小的 datetime/tzinfo 循环复现程序,并检查现有的 datetime 测试。完成的标准是循环在 gc.collect() 后被回收,并有一个覆盖该行为的回归测试。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- c, python
- 领域
- backend
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 45/100