Type narrowing fails for union of iterable and dictionary when using `isinstance(x, Iterable)` in a conditional
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
Bug Report
When using Union[Iterable[int], Dict[str, int]] together with isinstance(x, Iterable) in a conditional, the narrowing of the type does not work as expected. The previously correctly narrowed type is reverted to the un-narrowed type inside the branch.
To Reproduce
from typing import Dict, Iterable, Union
def test_iterable(x: Union[Iterable[int], Dict[str, int]]) -> Iterable[int]:
if isinstance(x, dict):
return [1, 2, 3]
reveal_type(x) # typing.Iterable[builtins.int]
if isinstance(x, Iterable):
reveal_type(x) # Union[typing.Iterable[builtins.int], builtins.dict[builtins.str, builtins.int]]
return x # mypy falsely returns an error here
Expected Behavior
The type of x should be correctly narrowed down to Iterable[int].
Actual Behavior
Running mypy returns:
example.py:10: error: Incompatible return value type (got "Union[Iterable[int], Dict[str, int]]", expected "Iterable[int]")
Found 1 error in 1 file (checked 1 source file)
The problem persists even if the second if is changed to elif.
Your Environment
I used a clean virtual environment to test, only mypy was installed.
- Mypy version used: 0.971
- Python version used: 3.9.5
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
Comienza con el reproducer de example.py y ejecuta mypy contra él para confirmar el error reportado con la unión y las comprobaciones isinstance. Sigue el comportamiento del estrechamiento de tipos hasta que la rama informe Iterable[int], como se espera, y verifica después que el ejemplo se complete sin el error de retorno incompatible.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- devtools
- Tipo de issue
- Error
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 45/100