python / python/mypy

Support enum member `value` types

Aperta
#8,722 6 commenti 20 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

feature priority-2-low topic-enum
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Not sure if this would be in mypy or the typeshed, though it may need support in both.

Currently enum.IntEnum provides a way to have an enum whose value is an int, however all other enum.Enums have a .value of Any.

While this can be worked around in more recent versions of Python by adding a member without a value within the enum:

class MyEnum(str, enum.Enum):
    value: str
    FIRST = 'first'

This isn't ideal as it means that there are two places where this needs to be specified -- as an inherited type and within the class body.

It feels like it would be better if mypy was able to infer the member value type from the inheritance.

Aside: had generics existed before Enum, it feels like that might alternatively solved this, something like:

class MyEnum(enum.Enum[str]):
    FIRST = 'first'

Edit:
Note that this issue is about the general use-case of variables typed for the enum (such as x: MyEnum) -- mypy has long supported determining the type of specific members and their .values (e.g: reveal_type(MyEnum.FIRST.value) is already str or more recently Literal['first']).

I've put a more complete demo of this at https://gist.github.com/PeterJCLaw/d4334e498ab1391ee306886748e675f1.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia esaminando la demo completa dell’issue e seguendo la gestione degli enum in mypy e typeshed; l’issue non identifica file o test specifici. Determina come dovrebbe essere inferito il tipo del valore di una variabile enum dall’ereditarietà, quindi aggiungi una copertura che dimostri che le istanze generiche di enum espongono il tipo del valore previsto senza un’annotazione separata nel corpo della classe.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
30/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.