python / python/cpython

Add _DuringGC functions for tp_traverse

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

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

interpreter-core topic-C-API type-feature
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Feature or enhancement

As seen in https://discuss.python.org/t/adding-c-api-for-use-in-tp-traverse/105331/13 and https://github.com/capi-workgroup/decisions/issues/95:

There are newly documented restrictions on tp_traverse:

The traversal function must not have any side effects. It must not modify the reference counts of any Python objects nor create or destroy any Python objects.

But, whether a C-API function modifies some reference count is an implementation detail that we can change at any time. Core devs can add logging, an audit event, or a warning, to virtually any function.
This implies that you can't safely use any C API function in tp_traverse, unless it guarantees that it has no side effects.

I propose to add such side-effect-free versions of some functions useful in tp_traverse, with a _DuringGC suffix -- namely:

  • PyObject_GetTypeData_DuringGC
  • PyObject_GetItemData_DuringGC
  • PyType_GetModuleState_DuringGC
  • PyModule_GetState_DuringGC
  • PyModule_GetToken_DuringGC
  • PyType_GetBaseByToken_DuringGC
  • PyType_GetModule_DuringGC
  • PyType_GetModuleByToken_DuringGC

Compared to their non-suffixed variants, the main difference is that we promise that these will remain safe to use in tp_traverse. The other differences are that these functions cannot fail, and (where applicable) they return borrowed references rather than strong ones.

Also, Py_VISIT, Py_SIZE, PyObject_VisitManagedDict as well as the visitproc that Python passes to tp_traverse will be documented to work like this.
[edit] I'll also include a few ones useful in these: PyObject_TypeCheck, PyType_IsSubtype, PyType_HasFeature, Py{<type>}_Check, Py{<type>}_CheckExact.

Users that call any _DuringGC function (including some type's tp_traverse) must manually must ensure that the type, MRO, and layout of any argument doesn't concurrently change. That means only calling them from tp_traverse.

Linked PRs
  • gh-145925

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

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

はじめの一歩

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

調査の方向性

まず、リンクされている C-API の議論、意思決定 issue 95、PR gh-145925 を読んでください。記載されている _DuringGC 関数と、関連する Py_VISIT、Py_SIZE、visitproc、型チェック API を確認してください。提案された副作用のない API と、それらの tp_traverse に対する安全性の保証が実装され、文書化されていれば完了です。

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

評価

技術スタック
c, python
領域
api, backend-api-design
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
25/100

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

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