python / python/mypy

Type narrowing for dict.get("key") is not None

Ouverte
#14,766 2 commentaires 4 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

feature topic-type-narrowing
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"])

Playground Link

Expected Behavior
According to the TypedDict, we have 3 cases for the Key my_optional_dict:

  1. The Dict did not have this Key (indicated by total=False
  2. The Value of this Key is None
  3. The Value of this Key is a DictA

If we look at the if in the test function, it does 2 things:

  1. Check if the Dict contains this Key
  2. 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

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. 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

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.