Skip to content

Support enum member value types #8722

@PeterJCLaw

Description

@PeterJCLaw

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions