python / python/mypy

Field of union needs to be different type when reading vs setting

Offen
#16,732 0 Kommentare 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug
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

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Ö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

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.