C API/GC: datetime.datetime doesn't have `Py_TPFLAGS_HAVE_GC`, potentially causing leaks in `tzinfo` cycles
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- 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