python / python/cpython

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

未关闭
#155,962 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

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. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

首先阅读 instance_has_key() 以及 gh-123219 引入的 specialization 更改。使用 dis.dis(f, adaptive=True) 运行该 issue 的 Python 复现代码,并验证替换 dict 后是否仍能进行预期的 LOAD_ATTR specialization;gh-155963 已经与这项工作关联。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
performance
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
描述清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。