Field of union needs to be different type when reading vs setting
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, das bereitgestellte Foo/Bar-Beispiel und die verlinkte mypy-play-Reproduktion auszuführen, um Feldzugriffe beim Lesen mit Zuweisungen auf einer Union zu vergleichen. Verfolge die relevante Prüfung von Zuweisungen an Union-Attribute und bestätige anschließend, dass das Problem behoben ist, wenn Zuweisungen nur akzeptiert werden, wenn sie für jedes Union-Mitglied gültig sind, und dass das gemeldete Beispiel einen Fehler erzeugt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100