python / python/mypy

Narrowing enums causes `.value` to be typed as `Any`

Abierto
#14,092 5 comentarios 2 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

bug topic-enum
Lenguaje dominante
Python
Estrellas
20.6k
Forks
3.3k
Métricas de merge de PR
Métricas de PR pendientes

Descripción

Bug Report

Apologies if this has already been reported, but I couldn't find an existing issue for it.

The issue I'm seeing is related to accessing the .value of an Enum after "narrowing" it with the is operator. It seems like the narrowing (to Union[Literal[...]]) works as expected, but then it fails to realize that the .value of all the variants have the same type (and so falls back to Any).

This only affects runs with --warn-return-any enabled:

$ mypy --config-file /dev/null --warn-return-any enum_narrowing.py

To Reproduce

It's probably easiest to see in this example:

import enum
from typing import Tuple

RGB = Tuple[int, int, int]

class Color(enum.Enum):
    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)

    def red(self) -> int:
        if self is Color.WHITE:
            return 255
        return self.value[0]  # error: Returning Any from function declared to return "int"

(playground URL: https://mypy-play.net/?mypy=latest&python=3.8&flags=warn-return-any&gist=b2a6df92fb37717e5c9d7542b6e88fec)

Expected Behavior

This should deduce that self.value has type RGB and succeed.

Actual Behavior

If I add some reveal_type(self) and reveal_type(self.value)s before/after the narrowing, I get this output:

enum_narrowing.py:11: note: Revealed type is "enum_narrowing.Color"
enum_narrowing.py:12: note: Revealed type is "Tuple[Literal[255]?, Literal[255]?, Literal[255]?]"
enum_narrowing.py:15: note: Revealed type is "Literal[enum_narrowing.Color.BLACK]"
enum_narrowing.py:16: note: Revealed type is "Any"

Your Environment

$ python --version
Python 3.8.0
$ mypy --version
mypy 0.991 (compiled: yes)

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 comando de mypy proporcionado contra enum_narrowing.py y compara los tipos revelados antes y después del estrechamiento mediante is. Sigue el estrechamiento de los miembros del enum y el manejo del tipo .value; la corrección está completa cuando self.value[0] se infiere como int y el ejemplo pasa con --warn-return-any.

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.