python / python/cpython

Improve guidelines for GC protocol implementation for heap types

オープン
#138,292 コメント 4 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

docs topic-C-API
主要言語
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_alloc instead of PyObject_New and PyObject_GC_New.
  • Use type->tp_free instead of PyObject_Free and PyObject_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:

What I am actually worried about is:

Constructors for container types must conform to two rules:

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

docs.python.org/3.14/c-api/gcsupport.html にある C API のガベージコレクションサポートのドキュメントから始め、特に tp_alloc、PyObject_GC_New、PyObject_GC_Track に関するガイダンスを確認してください。tp_alloc がオブジェクトを追跡するタイミングを説明するようにガイダンスを更新し、適切な場合は PyObject_GC_New ではなく tp_alloc を使用してください。文書化された構築規則に一貫性があれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
c, python
領域
documentation
issue の種類
ドキュメント
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。