`in` keyword should narrow Union[TypedDict, ...]
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia esaminando il narrowing esistente di mypy basato su isinstance, quindi ricostruisci come vengono validate le verifiche delle chiavi di Union e TypedDict. Il lavoro è completo quando un controllo in restringe la risposta al TypedDict corrispondente e l'esempio fornito supera la validazione senza cast().
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100