python / python/mypy

Enum member aliases does not work correctly with Literal

Ouverte
#8,657 6 commentaires 7 réactions 0 personnes assignées Voir sur GitHub

Personne n'a encore pris cette issue.

topic-enum
Langage dominant
Python
Étoiles
20.6k
Forks
3.3k
Métriques de merge des PR
Métriques de PR en attente

Description

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]

Guide de contribution

Ouvrir le guide de contribution

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Piste de recherche

Reproduisez les deux exemples de example.py et comparez les types révélés par mypy pour Color.BLACK, BLACK, BLACK_ALIAS et les annotations Optional[Literal[...]]. Suivez les chemins d'inférence de enum et de Literal, puis ajoutez une couverture de régression montrant que les alias préservent le type littéral de l'enum ; le travail est terminé lorsque les types révélés via les alias correspondent aux résultats directs de Color.BLACK.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
python
Domaine
developer-experience, tooling
Type d'issue
Bug
Difficulté
4/5
Temps estimé
3-5 jours
Activité
À l'abandon
Clarté
Plutôt claire
Accessibilité débutants
35/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.