python / python/mypy

mypy ignores type checking and produces error for union types when using `is` keyword to check the boolean result from `isinstance()`

Abierto
#14,289 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

feature topic-type-narrowing
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 the is True or is False keywords in the if statement along with isinstance, mypy does not recognize the type checking and produces an error, and ignores the instance type checking.

To Reproduce

from typing import Union

class A:
    prop: str = "Test"
    prop2: int = 999

class B:
    prop: str = "Test 2"

AB = Union[A, B]

if __name__ == '__main__':
    test_var: AB = A()

    if isinstance(test_var, A) is True:
        print(test_var.prop2)```

Playground: https://mypy-play.net/?mypy=latest&python=3.9&gist=7c4401069c861413b72a395a4ce92757

Expected Behavior

I expected that both expressions below were interpreted the same way by mypy as both are syntactically valid and produce the same result:

Using the is keyword to check the result:

    if isinstance(test_var, A) is True:
      pass

No is keyword:

    if isinstance(test_var, A):
      pass

Actual Behavior

main.py:19: error: Item "B" of "Union[A, B]" has no attribute "prop2"  [union-attr]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.991
  • Mypy command-line flags: --follow-imports silent
  • Mypy configuration options from mypy.ini (and other config files):
    •        python_version = 3.9
             warn_return_any = True
             warn_unused_configs = True
             ignore_missing_imports = True
             disallow_untyped_defs = True
             disallow_incomplete_defs = True
             check_untyped_defs = True
             disallow_untyped_decorators = True
             no_implicit_optional = True
             strict_equality = True
             warn_redundant_casts = True
             warn_unused_ignores = True
             show_error_codes = True
      
  • Python version used: 3.9

Guía de contribución

Abrir la guía de contribución

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Línea de trabajo

Comienza reproduciendo el ejemplo reportado en el mypy playground enlazado con Python 3.9 y mypy 0.991, comparando isinstance(test_var, A) con isinstance(test_var, A) is True. Rastrea cómo mypy acota los tipos unión para estas condiciones y añade una prueba de regresión; se considera terminado cuando ambas formas reconocen test_var como A sin el error de atributo de unión.

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
42/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.