python / python/mypy

Type-narrowing does not apply across 2 branches having the same condition within the same block

Ouverte
#7,928 2 commentaires 2 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

feature needs discussion priority-2-low 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

  • Are you reporting a bug, or opening a feature request?
    Feature request

  • Please insert below the code you are checking with mypy,

from typing import Optional

def my_func() -> bool:
  return True

created: bool = my_func()
a: Optional[int] = None
if created:
  a = 1
  z = a + 1 # This is OK

if created:
  x = a + 1 # Unsupported operand types for + ("None" and "int")
  • What is the actual behavior/output?
$ mypy a.py
a.py:13: error: Unsupported operand types for + ("None" and "int")
a.py:13: note: Left operand is of type "Optional[int]"
Found 1 error in 1 file (checked 1 source file)
  • What is the behavior/output you expect?

No errors. Mypy should be able to narrow the type of a to just int in the second if block, because it narrowed it to that type already the first if block and they have the exact same condition.

You can argue that it's easy to workaround it be merging the if blocks, but in real-life code, there could easily be intervening code that is not trivial to move around.

  • What are the versions of mypy and Python you are using?
    mypy 0.750+dev.5b73e2a5e62d3da723ac517fabacaa2a0c8cdf3c
    Python 3.7.4

  • What are the mypy flags you are using? (For example --strict-optional)
    --strict-optional

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 avec le reproducteur a.py et exécutez mypy avec --strict-optional pour confirmer le diagnostic actuel. Suivez le rétrécissement de type pour les deux blocs if created: répétés, puis ajoutez une couverture montrant que la deuxième utilisation de a est acceptée sans erreurs.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
python
Domaine
compilers, tooling
Type d'issue
Fonctionnalité
Difficulté
4/5
Temps estimé
3-5 jours
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
42/100

Recevez les nouvelles issues par e-mail

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