python / python/mypy

Enum member aliases does not work correctly with Literal

Abierto
#8,657 6 comentarios 7 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

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

Descripción

I'm not entirely sure whether this is a bug or missing feature related to the literals and enums but I think it is worth noticing.

Let's say that we have an enum and we define aliases for enum member outside of the enum's scope:

import enum

from typing import Literal

class Color(enum.Enum):

    BLACK = enum.auto()

BLACK = Color.BLACK
BLACK_ALIAS: Literal[Color.BLACK] = Color.BLACK

reveal_type(Color.BLACK)
reveal_type(BLACK)
reveal_type(BLACK_ALIAS)

Running mypy on above code results in following output:

example.py:12: note: Revealed type is 'Literal[Color.BLACK]?'
example.py:13: note: Revealed type is 'Color'
example.py:14: note: Revealed type is 'Literal[Color.BLACK]'

Now it's not idea that second reveal does not reveal Color.BLACK but it's also not that much of a problem since we can add Literal[Color.BLACK typehint and the see the expected result in third reveal. The bigger problem comes, when we want to use Literal on such aliases:

import enum

from typing import Literal, Optional

class Color(enum.Enum):

    BLACK = enum.auto()

BLACK = Color.BLACK
BLACK_ALIAS: Literal[Color.BLACK] = Color.BLACK

x: Optional[Literal[Color.BLACK]] = None
y: Optional[Literal[BLACK]] = None
z: Optional[Literal[BLACK_ALIAS]] = None

reveal_type(x)
reveal_type(y)
reveal_type(z)

Running mypy on above code results in following output:

example.py:16: note: Revealed type is 'Union[Literal[Color.BLACK], None]'
example.py:17: note: Revealed type is 'Union[Any, None]'
example.py:18: note: Revealed type is 'Union[Any, None]'

It's clear that mypy does not interfere those aliases correctly even those the BLACK_ALIAS seemed to be correctly revealed as Literal[Color.BLACK] previously. It would be really nice to have mypy reveal those types correctly.

Now, you might ask, why would you want to define such aliases in the first place? Well, the most probable scenario would be the idea of having a enum class that basically implements a null object pattern. In such cases, you probably don't want to expose the enum class itself to the user.

The most basic example would be this:

import enum

from typing import Literal

class _MissingType(enum.Enum):

    MISSING = enum.auto()

    def __repr__(self) -> str:
        return self.name

MISSING: Literal[_MissingType.MISSING] = _MissingType.MISSING

Now with such construct I don't want to expose _MissingType class but because MISSING alias is not always interfered correctly I cannot do that if I want to have correct typing information everywhere.

I came up with following "reasonable" workaround for the time being:

MissingLiteral = Literal[_MissingType.MISSING]

Which allows me to only expose MissingLiteral and use it in following way:

x: Optional[MissingLiteral] = None

The revealed type is of course Union[Literal[Color.BLACK], None]

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

Reproduce los dos ejemplos de example.py y compara los tipos revelados por mypy para Color.BLACK, BLACK, BLACK_ALIAS y las anotaciones Optional[Literal[...]]. Sigue las rutas de inferencia de enum y Literal y, después, añade cobertura de regresión que demuestre que los alias conservan el tipo literal del enum; se considera terminado cuando los tipos revelados mediante alias coinciden con los resultados directos de Color.BLACK.

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

Evaluación

Stack tecnológico
python
Área
developer-experience, tooling
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.