Improve guidelines for GC protocol implementation for heap types
還沒有人認領這個 Issue。
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 35.9k
- PR 合併指標
- PR 指標待擷取
描述
This is a follow-up to https://github.com/python/cpython/pull/125962 which added some guidelines:
- Use
type->tp_allocinstead ofPyObject_NewandPyObject_GC_New. - Use
type->tp_freeinstead ofPyObject_FreeandPyObject_GC_Del.
Those two recommendations were introduced to facilitate adding the Py_TPFLAGS_HAVE_GC flag to a heap type (those types must (should?) implement the GC protocol, at least according to the docs: https://docs.python.org/3/c-api/gcsupport.html#supporting-cycle-detection).
Now, the docs should indicate that:
type->tp_allocmay callPyObject_GC_Track, depending onPy_TPFLAGS_HAVE_GC. Some users could be surprised by this (like me in https://github.com/python/cpython/pull/138266).- https://docs.python.org/3.14/c-api/gcsupport.html#supporting-cycle-detection should be updated because it mentions using
PyObject_GC_New, which itself mentions usingtp_allocdirectly. Better to just mentiontp_alloc.
What I am actually worried about is:
Constructors for container types must conform to two rules:
- The memory for the object must be allocated using PyObject_GC_New or PyObject_GC_NewVar.
- Once all the fields which may contain references to other containers are initialized, it must call PyObject_GC_Track().
Now, tp_alloc automatically calls PyObject_GC_Track so users won't be able to pre-initialize fields, so I suggest that we mention this.
Outdated discussion
If people need to first initialize fields, maybe we should recommend constructing them first:
static PyObject *
object_new(PyTypeObject *type)
{
T *self = NULL;
PyObject *f1, *f2, *f3;
f1 = do1();
if (f1 == NULL) { goto error_pre_init; }
f2 = do2();
if (f2 == NULL) { goto error_pre_init; }
f3 = do3();
if (f3 == NULL) { goto error_pre_init; }
self = (T *)type->tp_alloc(type, 0);
if (self == NULL) {
goto error_pre_init;
}
self->f1 = f1;
self->f2 = f2;
self->f3 = f3;
f1 = f2 = f3 = NULL;
if (finalize(self) < 0) {
goto error;
}
return (PyObject *)self;
error_pre_init:
Py_XDECREF(f1);
Py_XDECREF(f2);
Py_XDECREF(f3);
return NULL;
error_post_init:
Py_DECREF(self);
return NULL;
}
cc @ZeroIntensity
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 docs.python.org/3.14/c-api/gcsupport.html 中的 C API 垃圾回收支援文件開始,特別關注有關 tp_alloc、PyObject_GC_New 和 PyObject_GC_Track 的指引。更新指引,說明 tp_alloc 何時會追蹤物件,並在適當情況下使用 tp_alloc 而不是 PyObject_GC_New;當文件化的建構規則一致時即完成。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- c, python
- 領域
- documentation
- Issue 類型
- 文件
- 難度
- 3/5
- 預估耗時
- 1-2 天
- 活躍度
- 停滯
- 描述清晰度
- 基本清楚
- 新手友好度
- 35/100