python / python/typing

Generic versions of enum.Enum?

Abierto
#535 15 comentarios 65 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

topic: feature
Lenguaje dominante
Python
Estrellas
1.8k
Forks
302
Merge medio
23 h
PR fusionados (30 d)
8

Descripción

(First of all, apologies if this is not the proper place for suggesting this, or if this has already been discussed, I couldn't find anything related to this so I opened an issue here.)

So I've recently come across a situation like this:
I've defined an enum

from enum import Enum

class MyEnum(Enum):
    a = 1
    b = 2
    c = 3

and need to use the value of an enum member later on:

some_func(MyEnum.a.value)

Analyzing this with mypy highlights the value of MyEnum.a.value as Any. That makes sense, as enum member values could be of any type.
However, in this case I know that all members of my enum should have int values, and no other type. In general, in most cases where I have used an enum the values have all been of a single type. I'd like to communicate this to the typing system somehow, but it doesn't seem possible with enum.Enum.

Changing the enum's type to enum.IntEnum lets mypy identify the value as int, however, using IntEnum is discouraged by the enum module documentation since it also makes enums comparable to other enums and to integers, which wouldn't actually be necessary for this use case. So as far as I understand using IntEnum wouldn't be ideal either.

Casting the .value to an int works, but it's more a workaround than a solution, and I hope this could somehow be done without casting.

To me, it seems this could be solved by introducing a generic Enum type in typing, similar to Sequence[T] and the other generics defined there.
With this, the code would look like

from typing import Enum

class MyEnum(Enum[int]):
    a = 1
    b = 2

some_func(MyEnum.a.value)

This could make the intent of the enum more clear, and would allow people to catch errors that would be introduced by defining an enum member with a different value type. It also would allow static checkers to infer the type of the enum member's value without having to use casts. Comparison operations would work the same way as for enum.Enum, and unlike enum.IntEnum.

If something like this could be considered for the typing module I'd be very grateful.

(Also, lastly, thanks for all the work on static typing in Python. It's helped me catch several bugs in my code so far, and I'm working on fully converting my project to make use of static typing, since it's been such a great help so far.)

Guía de contribución

No hay ninguna guía de contribución indexada para este repositorio

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

No se nombran archivos del repositorio, pruebas ni puntos de entrada de la implementación. Empieza revisando el comportamiento genérico propuesto de Enum[int] en relación con el debate existente sobre el tipado de Enum e IntEnum; para completarlo se requerirían un diseño acordado y la implementación y las pruebas correspondientes para la inferencia del tipo de valor y los valores mixtos de los miembros.

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

Evaluación

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

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.