LOAD_ATTR does not specialize after replacing an instance's `__dict__`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading instance_has_key() and the specialization change introduced by gh-123219. Run the issue's Python reproduction with dis.dis(f, adaptive=True) and verify that replacing dict still permits the expected LOAD_ATTR specialization; gh-155963 is already linked to this work.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- performance
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 25/100