python / python/cpython

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

Aperta
#155,962 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

3.14 3.15 3.16 interpreter-core performance type-bug
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia leggendo instance_has_key() e la modifica alla specializzazione introdotta da gh-123219. Esegui la riproduzione Python dell'issue con dis.dis(f, adaptive=True) e verifica che la sostituzione di dict consenta ancora la specializzazione LOAD_ATTR prevista; gh-155963 è già collegato a questo lavoro.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
performance
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.