Type narrowing for dict.get("key") is not None
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
See Code and Explanation below
To Reproduce
from typing import TypedDict, Optional
class DictA(TypedDict):
my_value: str
class DictB(TypedDict, total=False):
my_optional_dict: Optional[DictA]
def test(arg: DictB) -> None:
if arg.get("my_optional_dict") is not None:
print(arg["my_optional_dict"]["my_value"])
Expected Behavior
According to the TypedDict, we have 3 cases for the Key my_optional_dict:
- The Dict did not have this Key (indicated by
total=False - The Value of this Key is
None - The Value of this Key is a
DictA
If we look at the if in the test function, it does 2 things:
- Check if the Dict contains this Key
- Check if the value is not None
This means, that the my_optional_dict of arg is always of the type DictA, so mypy should not see a problem here.
Actual Behavior
main.py:14: error: Value of type "Optional[DictA]" is not indexable [index]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 1.0.0
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.11.1
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 eseguendo il riproduttore TypedDict fornito con mypy usando l'esempio Python 3.11 indicato e senza flag di configurazione. Traccia come il type checker restringe arg.get("my_optional_dict") dopo il controllo di None, quindi aggiungi un test di regressione basato su test() che passi senza un errore di indicizzabilità.
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