Type narrowing for dict.get("key") is not None
Personne n'a encore pris cette issue.
- Langage dominant
- Python
- Étoiles
- 20.6k
- Forks
- 3.3k
- Métriques de merge des PR
- Métriques de PR en attente
Description
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
Guide de contribution
Ouvrir le guide de contribution
Par où commencer
- Lisez l'issue en entier, puis le guide de contribution du projet.
- Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
- Forkez le dépôt et travaillez sur une branche.
- Ouvrez une pull request qui référence le numéro de l'issue.
Piste de recherche
Commencez par exécuter le reproducteur TypedDict fourni avec mypy en utilisant l’exemple Python 3.11 indiqué et sans indicateurs de configuration. Suivez la manière dont le vérificateur de types restreint arg.get("my_optional_dict") après la vérification de None, puis ajoutez un test de régression basé sur test() qui réussit sans erreur d’indexabilité.
Rédigé par le modèle d'indexation à partir du texte de l'issue.
Évaluation
- Stack technique
- python
- Domaine
- devtools
- Type d'issue
- Bug
- Difficulté
- 4/5
- Temps estimé
- 3-5 jours
- Activité
- À l'abandon
- Clarté
- Plutôt claire
- Accessibilité débutants
- 35/100