Type refinement does not work with `None in [a, b, c]`, `any()`, or `all()` checks

Abierto
#17,149 2 comentarios 1 reacción 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
5/5
Tiempo estimado
Más de una semana
Aptitud para principiantes
35/100
Tipo de issue
Nueva funcionalidad
Claridad
Bastante claro
Estado de actividad
Estancado
Stack tecnológico
python
Área
compilers

Línea de trabajo

Comienza con los ejemplos reproducibles para las comprobaciones de pertenencia de None y las comprobaciones de all() y, después, sigue el manejo del refinamiento de tipos de mypy para estas expresiones condicionales. Se considera terminado cuando las variables indicadas se han reducido de Optional[str] y Optional[int] después de las comprobaciones, sin los errores mostrados.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug topic-type-narrowing

When checking if multiple variables are not None using the syntax None in [a, b, c], mypy fails to refine the types of these variables to non-Optional types after this check. This issue persists even when using any() or all() for similar checks, preventing mypy from correctly inferring that the variables cannot be None past these checks, despite the code logically ensuring that these variables are not None.

Code to Reproduce:

from typing import Optional

def init_vars(
    a: Optional[str] = None,
    b: Optional[int] = None,
    c: Optional[int] = None,
) -> None:
    if None in [a, b, c]:
        raise ValueError("a, b, and c cannot be None")
    
    # Expected: a, b, c should not be Optional types beyond this point
    # Actual: mypy still treats a, b, c as Optional types
    print(a.upper())  # mypy error: Item "None" of "Optional[str]" has no attribute "upper"
    print(b + 1)      # mypy error: Unsupported operand type(s) for +: 'int' and 'NoneType'
    print(c + 1)      # mypy error: Unsupported operand type(s) for +: 'int' and 'NoneType'

And here is another example with the all function (with any it is quite similar):

def init_vars_with_all(
    a: Optional[str] = None,
    b: Optional[int] = None,
    c: Optional[int] = None,
) -> None:
    if not all(x is not None for x in [a, b, c]):
        raise ValueError("a, b, and c cannot be None")

    # Expected: a, b, c should not be Optional types beyond this point
    # Actual: mypy still treats a, b, c as Optional types
    print(a.upper())  # mypy error: same as above
    print(b + 1)      # mypy error: same as above
    print(c + 1)      # mypy error: same as above
Expected Behavior:

After the checks if None in [a, b, c]: or using all(), mypy should refine the types of a, b, and c to str, int, and int respectively, acknowledging that they cannot be None.

Actual Behavior:

mypy does not refine the types and continues to treat a, b, and c as Optional[str], Optional[int], and Optional[int] respectively. This results in type errors when attempting to use these variables in a context that does not allow None.

Additional Information:

mypy version: 1.9.0 compiled
Python version: 3.10
No flags or configurations are altering the default behavior of mypy in this instance.

This behavior suggests a limitation in mypy's type inference system when it comes to using collective None checks with list membership or aggregate functions like any() and all(). An enhancement to allow type refinement in such cases would significantly improve usability in scenarios involving initialization checks for multiple variables.

Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Merge medio
1 d 18 h
PR fusionados (30 d)
54

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.

Más de python/mypy

Todos los issues de python/mypy

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.