python / python/mypy

False positive `[operator]` on union of dicts with heterogeneous value types

Offen
#18,236 3 Kommentare 1 Reaktion 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-type-context
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

If I take the union of two dicts with different value types, I cannot assign the result to a variable that is annotated with the resulting type. Doing so causes an error. Assigning to an non-annotated variable does not cause an error, which seems like the correct behavior.

Do I really need the annotation on d5 below? No. But I have a non-toy example of this in a code base where d5 is a type annotated attribute on an object, which results in the same error.

d1: dict[str, str] = {}
d2: dict[str, str | None] = {}

d3 = d1 | d2
reveal_type(d3)  # builtins.dict[builtins.str, Union[builtins.str, None]], aka dict[str, str | None]

# This is fine
d4: dict[str, str | None] = d3  # aka d1 | d2

# This isn't?
d5: dict[str, str | None] = d1 | d2

To Reproduce

See: https://mypy-play.net/?mypy=master&python=3.13&flags=show-error-codes&gist=2643cb3ff1ea956a1c4ed0869140d46d

Expected Behavior

I expect d5: dict[str, str | None] = d1 | d2 to be legal.

Actual Behavior

error: Unsupported operand types for | ("dict[str, str]" and "dict[str, str | None]") [operator].

Your Environment

  • Mypy version used: 1.13.0
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12

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 mit der minimalen Reproduktion im Issue oder dem darin verlinkten mypy-play-Beispiel und verwende dabei den angegebenen Kontext mit Python 3.12 und mypy 1.13.0. Vergleiche die annotierte direkte Union mit dem Fall der Zwischenvariable und überprüfe anschließend, dass die direkte Zuweisung nicht mehr den [operator]-Fehler ausgibt, während der aufgelöste Typ weiterhin dict[str, str | None] lautet.

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
45/100

Neue Issues direkt in Ihr Postfach

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