Strange behavior using Tagged Union
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
Bug Report
When using tagged unions, mypy infers correctly with with instance["tag"],
but fails with instance.get("tag")
To Reproduce
- Write the following code into
tagged_union.py:
from typing import Literal, TypedDict, Union
class TaggedTypeA(TypedDict):
tag: Literal["A"]
is_a: bool
class TaggedTypeB(TypedDict):
tag: Literal["B"]
TaggedUnion = Union[TaggedTypeA, TaggedTypeB]
instance_a: TaggedUnion = {"tag": "A", "is_a": True}
if instance_a["tag"] == "A":
print(f"Am I type a? {instance_a['is_a']}")
if instance_a.get("tag") == "A":
print(f"Am I type a this time? {instance_a['is_a']}")
- Run
mypy tagged_union.py - Get only one error
tagged_union.py:21: error: TypedDict "TaggedTypeB" has no key "is_a"
Error occurs in second if statement
Expected Behavior
I can see that mypy correctly infers the type of instance_a when I use instance_a["tag"] == "A" (the first if expression).
Therefore, I would expect the same behavior when using instance_a.get("tag") == "A" (the second if clause).
Actual Behavior
mypy correctly infers the type of instance_a when I use instance_a["tag"] == "A" (the first if expression).
mypy fails to infer the type when I use instance_a.get("tag") == "A".
In fact, mypy doesn't only not infer the correct type, it infers the opposite type TaggedTypeB which does not make sense at all
Your Environment
- Mypy version used: 0.902
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.8.10
- Operating system and version: Ubuntu 21.04
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 con la riproduzione di tagged_union.py ed esegui mypy tagged_union.py per confrontare il narrowing per l'accesso con parentesi quadre e get(). Traccia il percorso di narrowing dei tipi responsabile delle unioni di TypedDict, quindi aggiungi o aggiorna un test di regressione che mostri che entrambe le forme vengono ristrette a TaggedTypeA e superano la suite di test mypy pertinente.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100