Set and Dict generalizing the type unnecessarily
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
See these two example functions:
def f(items: list[str] | list[int]) -> None:
items_as_set: set[str] | set[int] = set(items)
def g(key_to_count: dict[str, float] | dict[int, float]) -> None:
key_to_count_2: dict[str, float] | dict[int, float] = {k: v for k, v in key_to_count.items()}
Mypy 1.10.0 complains about the assignment in each of them:
test_mypy_dict.py:2: error: Incompatible types in assignment (expression has type "set[object]", variable has type "set[str] | set[int]") [assignment]
test_mypy_dict.py:5: error: Incompatible types in assignment (expression has type "dict[str | int, float]", variable has type "dict[str, float] | dict[int, float]") [assignment]
To Reproduce
Playground gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=83bde5f3f11470e94b6a680158649641
Expected Behavior
The set() or dict() operation applied on a variable that is either a list[str] | list[int] is always either a set[str] or set[int]. The same applies to function g using a dict. Thus the functions should not raise a mypy error.
Workarounds
I tried two workarounds:
- Using a mixed type of
list[str | int]. However, I get the typelist[str] | list[int]by an external function, thus this is not compatible. - Using a generic. This is not working either.
See the playground gist: https://mypy-play.net/?mypy=latest&python=3.12&gist=264490179628a0a214a2e5bd947b8ccf
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, die beiden Python-Reproduktionen aus dem Issue auszuführen, einschließlich der verknüpften mypy-play-Beispiele, und vergleiche die inferierten Typen und Zuweisungsfehler für set() und die dict comprehension. Verfolge den Type-Checking-Pfad für diese Konstruktor- und Comprehension-Ausdrücke; abgeschlossen ist die Aufgabe, wenn beide Funktionen fehlerfrei typgeprüft werden und dabei die Union homogener Containertypen erhalten bleibt.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers, devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100