Dict literal of type `A` cannot be assigned to variable of type `A | B` (incompatible type error)
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 fails with unions of a union of dict types with literal keys: a dict literal which can be assigned to a variable of type A cannot be assigned to a variable of type A | B.
To Reproduce
Gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=4564762bf0284f05695be7fc30c79020
from typing import Literal
A = dict[Literal["foo"], str]
B = dict[Literal["bar"], int]
a: A = {"foo": "s"} # works
b: B = {"bar": 5} # works
T = A | B
t1: T = {"foo": "s"} # error
t2: T = {"bar": 5} # error
Expected Behavior
It should work without errors.
Actual Behavior
main.py:10: error: Incompatible types in assignment (expression has type "dict[str, str]", variable has type "dict[Literal['foo'], str] | dict[Literal['bar'], int]") [assignment]
main.py:11: error: Incompatible types in assignment (expression has type "dict[str, int]", variable has type "dict[Literal['foo'], str] | dict[Literal['bar'], int]") [assignment]
Your Environment
- Mypy version used: 1.11.0
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.12
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, mypy für das minimale Beispiel in main.py auszuführen, und verwende die verlinkte mypy-play-Reproduktion, um das Verhalten zu bestätigen. Verfolge die Verarbeitung von dict-Literalen, die Unions von dict-Typen zugewiesen werden, und ergänze Tests, die zeigen, dass beide Zuweisungen ohne Fehler durchlaufen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- tooling
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100