Type-narrowing does not apply across 2 branches having the same condition within the same block
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 20.6k
- Forks
- 3.3k
- Métricas de merge de PR
- Métricas de PR pendientes
Descripción
-
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
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Empieza con el reproductor a.py y ejecuta mypy con --strict-optional para confirmar el diagnóstico actual. Rastrea el estrechamiento de tipos para los dos bloques if created: repetidos y, después, añade cobertura que muestre que el segundo uso de a se acepta sin errores.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- compilers, tooling
- Tipo de issue
- Nueva funcionalidad
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 42/100