Skip to content

LOAD_ATTR does not specialize after replacing an instance's __dict__ #155962

Description

@koxudaxi

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions