python / python/mypy

Enum member aliases does not work correctly with Literal

Aperta
#8,657 6 commenti 7 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

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]

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

Riproduci i due esempi in example.py e confronta i tipi rivelati da mypy per Color.BLACK, BLACK, BLACK_ALIAS e le annotazioni Optional[Literal[...]]. Segui i percorsi di inferenza di enum e Literal, quindi aggiungi una copertura di regressione che dimostri che gli alias preservano il tipo literal dell'enum; il lavoro è completato quando i tipi rivelati tramite gli alias corrispondono ai risultati diretti di Color.BLACK.

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

Valutazione

Stack tecnologico
python
Ambito
developer-experience, tooling
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.