python / python/mypy

`in` keyword should narrow Union[TypedDict, ...]

Offen
#9,953 5 Kommentare 5 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

Feature

Using in on a Union[TypedDict] should narrow the Union. There is already something similar for isinstance that can narrow based on types. If a certain key exists you could narrow down that your types from a Union as well. This would prevent an error saying a certain key is missing because you checked already, they code can safely access the key. Currently the only workaround for this would be to use cast() but really shouldn't be necessary.

Pitch

After the change the following code should pass validation.

from typing import castm Union
from typing_extensions import TypedDict

class Movie(TypedDict):
    name: str
    year: int

class MovieResponse(TypedDict):
    movie: Movie

class Book(TypedDict):
    name: str
    year: int

class BookResponse(TypedDict):
    book: Book

MediaResponse = Union[MovieResponse, BookResponse]

response : MediaResponse = MovieResponse(movie=Movie(name="Blade Runner", year=1982))

if 'movie' in response:
    reveal_type(response)  # Current: Union[MovieResponse, BookResponse]
                           # Desired: Union[MovieResponse]
    print(response["movie"])  # This fails due to `BookResponse` not having a key "movie"
                              # but we already validated existance of the 'movie' key and that type
                              # should no longer be considered here
    print(cast(MovieResponse, response)["movie"])  # current workaround

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 Untersuchung von mypy's bestehender isinstance-basierter Eingrenzung und verfolge anschließend, wie Union- und TypedDict-Schlüsselprüfungen validiert werden. Die Arbeit ist abgeschlossen, wenn eine in-Prüfung die Antwort auf das passende TypedDict eingrenzt und das bereitgestellte Beispiel die Validierung ohne cast() besteht.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
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.