False positive with variable key in Mapping with Optional value
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 a mapping with an Optional value type, accessing a value using a variable key instead of a literal key prevents a None check from working properly.
To Reproduce
- Put the following code in
test.py:
from typing import Mapping, Optional
FOO: str = "foo"
def func(text: str) -> None:
_ = text
data: Mapping[str, Optional[str]] = {FOO: "bar"}
if data[FOO] is not None:
func(data[FOO]) # Line 11
if data["foo"] is not None:
func(data["foo"])
- Run
mypy test.py
Expected Behavior
mypy should not output any errors. As the above example shows, using a string literal instead of a variable containing a string does not cause any errors, even though the code is otherwise identical. The "Optional types and the None type" section of the documents says "supported checks for guarding against a None value include if x is not None", so this code should work.
Actual Behavior
mypy outputs the following:
test.py:11: error: Argument 1 to "func" has incompatible type "Optional[str]"; expected "str" [arg-type]
Your Environment
- Mypy version used:
0.812 - Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files):show_error_codes = True - Python version used:
3.7.9 - Operating system and version: macOS 10.15.7 (19H524)
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 reproducer de test.py y ejecuta mypy test.py para confirmar que los casos de clave variable y clave literal difieren. Traza el recorrido de comprobación de tipos para el acceso a Mapping y el estrechamiento de Optional; después, añade una prueba de regresión que cubra el caso de clave variable. Se considera terminado cuando ambas llamadas protegidas pasan la comprobación de tipos sin errores.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- compilers, devtools
- Tipo de issue
- Error
- Dificultad
- 4/5
- Tiempo estimado
- 3-5 días
- Estado de actividad
- Estancado
- Claridad
- Bien especificado
- Aptitud para principiantes
- 35/100