Mypy: Support enum member `value` types

Created on 25 Apr 2020  路  3Comments  路  Source: python/mypy

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'
feature priority-2-low topic-plugins

Most helpful comment

@A5rocks that seems evil, I think mypy should flag that as an error.

All 3 comments

I think this could be handled by updating the enums plugin? (It might possibly need some supporting typeshed change also?)

If this to be added, maybe consider supporting this:

import enum

class Blah(int, enum.Enum):
    foo = '5'

print(repr(Blah.foo.value))  # would print `5`
reveal_type(Blah.foo.value)  # reveals "str" but should reveal "int"
# https://mypy-play.net/?mypy=latest&python=3.8&gist=46ca47b0d534d00f2218c8835783b8c2

I'm pretty sure this is an intended use of Enums? I'm not sure :P

@A5rocks that seems evil, I think mypy should flag that as an error.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Stiivi picture Stiivi  路  3Comments

JelleZijlstra picture JelleZijlstra  路  4Comments

ikonst picture ikonst  路  3Comments

arquolo picture arquolo  路  3Comments

takeda picture takeda  路  3Comments