python / python/mypy

Problems with `get` on a TypedDict

Offen
#20,138 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

Bug Report

This bug is a bit hard to describe, so you should take a look at the test code. Feel free to edit the title.

As you can see in the test code, a expects dict[Literal["exclude"], list[str]]. test_dict, which is passed to b has a opional key named key with this type. As this type is optional, we use get here. Get returns {"exclude": []}) in case key does not exists in test_dict. {"exclude": []}) fits the type dict[Literal["exclude"], list[str]] but Mypy think it does not fit.

This bug does not exists in Mypy 1.17.

To Reproduce

https://mypy-play.net/?mypy=1.18.2&python=3.12&gist=932063170e6ad2c3ab798153870b82d4

Expected Behavior

Mypy should not find any errors

Actual Behavior

main.py:13: error: Argument 1 to "a" has incompatible type "dict[Literal['exclude'], list[str]] | dict[str, list[Never]]"; expected "dict[Literal['exclude'], list[str]]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Your Environment

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

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 verknüpften mypy-play-Reproduktion in main.py und führe sie mit mypy 1.17 und 1.18.2 aus, um die Regression einzugrenzen. Verfolge, wie get-Ausdrücke für optionale Schlüssel von TypedDict ihren Fallback-Typ inferieren; als abgeschlossen gilt die Aufgabe, wenn die Reproduktion keine Fehler erzeugt und dabei die korrekte Typprüfung beibehält.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
30/100

Neue Issues direkt in Ihr Postfach

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