Field of union needs to be different type when reading vs setting
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
Bug Report
Mypy appears to infer that the type of a field of a variable that is typed as a union is a single type whether that field is being read or updated. The type correct when reading the field (union of the types of the fields) , but not correct when setting as it does not enforce that the value being assigned needs to be valid for both of the types in the union (intersection of the types of the fields).
To Reproduce
class Foo:
a: int
class Bar:
a: str
either: Foo | Bar
either.a = 1 # No error, despite not being valid for Bar
More detailed example: https://mypy-play.net/?mypy=latest&python=3.12&gist=bf74f1ba35979f10b1878b2e1abca865
Expected Behavior
Mypy should report the assignment as an error if it does not work with all the types in the union.
Actual Behavior
No error, despite the assignment allowing a field of type str to be an int
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia eseguendo l’esempio Foo/Bar fornito e la riproduzione collegata di mypy-play per confrontare le letture dei campi con le assegnazioni su una union. Traccia il controllo pertinente delle assegnazioni degli attributi di una union, quindi conferma che il problema è risolto quando le assegnazioni vengono accettate solo se sono valide per ogni membro della union e l’esempio segnalato produce un errore.
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
- 35/100