Dzeri96
Dzeri96

Reputation: 433

Python type hint enum member value

I'm trying to constrain an enum to have all member values of only one type. For example, I want

class MyTypedEnum(Enum):
    MEMBER_1= 1
    MEMBER_2= 2
    ...

to be an enum with only ints in its members' values.

Therefore, when I write MyTypedEnum.MEMBER_X.value into my IDE, it recognizes that the type is indeed int.

Edit: This is obviously a simple example with int, but I'd like to use any type in its place.

Upvotes: 4

Views: 4014

Answers (1)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95948

As far as I can tell, the Python typing spec doesn't address this.

This is really going to depend on your IDE and static analysis tool. If I do:

from enum import Enum

class Foo(Enum):
    bar: int = 1
    baz: int = 2

reveal_type(Foo.bar.value)
value: int = Foo.bar.value

Then mypy understands it just fine, and gives me:

(py39) Juans-MacBook-Pro:~ juan$ mypy test.py
test.py:6: note: Revealed type is "builtins.int"

However, pyright gives me an error:

(py39) Juans-MacBook-Pro:~ juan$ pyright test.py
Found 1 source file
/Users/juan/Coursera/test.py
  /Users/juan/Coursera/test.py:4:16 - error: Expression of type "Literal[1]" cannot be assigned to declared type "Literal[Foo.bar]"
    "Literal[1]" cannot be assigned to type "Literal[Foo.bar]" (reportGeneralTypeIssues)
  /Users/juan/Coursera/test.py:5:16 - error: Expression of type "Literal[2]" cannot be assigned to declared type "Literal[Foo.baz]"
    "Literal[2]" cannot be assigned to type "Literal[Foo.baz]" (reportGeneralTypeIssues)
  /Users/juan/Coursera/test.py:6:13 - info: Type of "Foo.bar.value" is "int"
2 errors, 0 warnings, 1 info
Completed in 0.819sec

I imagine mypy is special-casing enums.

I found this semi-related issue in the pyright github.

And here is a related PR from mypy where they added an inference feature for untyped enum values.

Upvotes: 6

Related Questions