python / python/cpython

LOAD_ATTR does not specialize after replacing an instance's `__dict__`

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

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

3.14 3.15 3.16 interpreter-core performance type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

Bug report

Bug description:

Replacing an instance's __dict__ prevents LOAD_ATTR from specializing on Python 3.14 and current main. The same case specializes to LOAD_ATTR_WITH_HINT on Python 3.13.

import dis

class C:
    pass

obj = C()
obj.__dict__ = {"x": 1}

def f():
    return obj.x

for _ in range(100):
    assert f() == 1

dis.dis(f, adaptive=True)

Observed result:

3.13: LOAD_ATTR_WITH_HINT
3.14: LOAD_ATTR
main: LOAD_ATTR

instance_has_key() checks Py_TPFLAGS_INLINE_VALUES on the type and then searches the type's shared keys. After __dict__ has been replaced, however, the instance no longer uses its inline values. The attribute is present in the attached dictionary but not necessarily in the shared keys, so specialization is skipped.

This appears to have started with gh-123219, which introduced instance_has_key() in Python 3.14. I reproduced it on current main at f40043e0953323675843a3c275511596f30c80e9.

This affects Pydantic v2 models because pydantic-core installs validated fields by replacing the model's __dict__. In a fresh-process datamodel-code-generator benchmark with 500 JSON Schema definitions, a local prototype reduced median runtime from 354.5 ms to 327.7 ms across 11 alternating samples.

CPython versions tested on:

CPython main branch

Operating systems tested on:

macOS

Linked PRs
  • gh-155963

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

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

はじめの一歩

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

調査の方向性

まず instance_has_key() と、gh-123219 で導入された特殊化の変更を読んでください。dis.dis(f, adaptive=True) を使って issue の Python 再現コードを実行し、dict を置き換えても期待される LOAD_ATTR の特殊化が引き続き可能であることを確認してください。この作業にはすでに gh-155963 が関連付けられています。

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

評価

技術スタック
python
領域
performance
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
25/100

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

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