python / python/mypy

Type narrowing when condition is assigned to a variable

Abierto
#11,979 2 comentarios 3 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

Narrowing techniques perform very well when the condition is calculated inside the if condition. When these are made outside, I can understand that mypy cannot guarantee that the narrow will be ok as the boolean value of the condition might be changed before reaching the if statement. However, when the value of this condition is given outside of the if statement but defined as a Final type, the narrow should be working

Minimal code to repdroduce it:

from typing import Optional, Final

def example_func(value: Optional[int] = None):

    condition: Final = value is not None

    if condition: 
        reveal_type(value)  # Revealed type is "Union[builtins.int, None]"
        value = value + 1   # MYPY ERROR

    if value is not None:
        reveal_type(value)  # Revealed type is "builtins.int"
        value = value + 1   # MYPY OK
    return 0

Expected Behavior
The type of value for the first if statement should be builtins.int, as the condition variable should remain with the same value that was previously assigned to it.

Actual Behavior
Narrowed not performed, and thus the type of value is still inferred as Optional[int]

Your Environment

  • Mypy version used: 0.931
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: Python 3.8.10
  • Operating system and version: Ubuntu 20

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 ejecutando el ejemplo mínimo de Python con mypy 0.931 e inspecciona los dos resultados de reveal_type alrededor de la condición Final. Rastrea el comportamiento del estrechamiento de tipos para las condiciones asignadas a variables Final; se considera terminado cuando el primer reveal_type informa de builtins.int y se acepta la suma siguiente sin debilitar el comportamiento existente para las condiciones directas.

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
Bastante claro
Aptitud para principiantes
45/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.