python / python/mypy

Mypy 1.7.0 makes two incorrect inferences about dataclass descriptor-based fields

Aperta
#16,538 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-dataclasses topic-descriptors
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug Report

When a dataclass field uses a descriptor, Mypy makes two incorrect inferences:

  1. If the descriptor has no default value (it raises AttributeError when accessed on the class), mypy incorrectly assumes it has a default and raises an error on the next field with no default value. The no-default mechanism was documented in Python 3.10 but has been there since 3.7. The specific code is in dataclasses._get_field, as default = getattr(cls, a_name, MISSING).
  2. If the descriptor-based field is typed with InitVar, mypy incorrectly assumes the attribute does not exist on the class.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=8a47d8538f2fc798a8564d30dae6434e

Expected Behavior

No error, matching runtime behaviour and the internal validations of the @dataclass decorator.

Actual Behavior

Two incorrect errors:

  1. Attributes without a default cannot follow attributes with one [misc]
  2. "Example2" has no attribute "this_exists" [attr-defined]

Your Environment

  • Mypy version used: 1.7.0 and 1.6.1
  • Python version used: 3.9 and 3.11

Related: #13856 describes another dataclass descriptor bug, fixed in mypy 1.2.

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 dalla riproduzione collegata di mypy-play e confronta i suoi due errori segnalati con il comportamento dei descrittori documentato intorno a dataclasses._get_field. Traccia il percorso del controllo dei tipi delle dataclass per i campi descrittore, incluso InitVar, e aggiungi una copertura mirata per entrambi i casi. Il lavoro è completato quando mypy non segnala errori per la riproduzione nelle versioni di Python interessate.

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

Valutazione

Stack tecnologico
python
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
38/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.