"Cannot determine type" if first assignment to attribute is unreachable
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
To Reproduce
Run mypy on the following code:
class C:
def __init__(self, a: str) -> None:
if a is None:
self.x = 123
else:
self.x = 456
It will output:
testcase.py:6: error: Cannot determine type of 'x'
Line 6 contains the second assignment to self.x.
Expected Behavior
mypy should be able to determine that the type of C.x is int.
Actual Behavior
The fact that a is annotated as str means that mypy determines that a is None is never true and therefore the first assignment to self.x is unreachable. The problem disappears if a is annotated as Optional[str].
So it looks like mypy half-ignores the first assignment to self.x: it doesn't use the type information available there since the code is unreachable, but it still considers it the assignment that determines the type of self.x.
Your Environment
mypy 0.790 with default configuration, running on Python 3.8.5 on openSUSE Linux.
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 reproductor de Python proporcionado y sigue la inferencia de tipos de mypy para la primera asignación de atributo cuando el flujo de control marca esa rama como inalcanzable. Confirma la corrección volviendo a ejecutar mypy en el ejemplo: C.x debería inferirse como int sin errores, mientras que el caso Optional[str] debería seguir funcionando.
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
- 3/5
- Tiempo estimado
- 1-2 días
- Estado de actividad
- Estancado
- Claridad
- Bastante claro
- Aptitud para principiantes
- 45/100