How to type hint Enums in Python
Type hint Enums in Python Use the enumeration class to type hint an enum in Python. You can then access any member of the enum in the body of the function without getting a warning.
Type hint Enums in Python
Use the enumeration class to type hint an enum in Python.
You can then access any member of the enum in the body of the function without getting a warning.
from enum import Enum
class Sizes(Enum):
SMALL = 1
MEDIUM = 2
LARGE = 3
def get_value_from_enum(size: Sizes):
print(size.name) # ๐๏ธ MEDIUM
print(size.value) # ๐๏ธ 2
return size.value
result = get_value_from_enum(Sizes.MEDIUM)
print(result) # ๐๏ธ 2
We used theย Sizes
enumeration class to type hint an enum.
Using the Literal
type instead
An alternative approach is to use the Literal
type to specify that the function argument can be one of the members in the enum.
from typing import Literal
from enum import Enum
class Sizes(Enum):
SMALL = 1
MEDIUM = 2
LARGE = 3
def get_value_from_enum(size: Literal[Sizes.SMALL, Sizes.MEDIUM, Sizes.LARGE]):
print(size.name) # ๐๏ธ MEDIUM
print(size.value) # ๐๏ธ 2
return size.value
result = get_value_from_enum(Sizes.MEDIUM)
print(result) # ๐๏ธ 2
Theย Literal Type hint can be used to indicate to type checkers that the function parameter has a value equal to the provided literal (or one of several literals like in the example).
# Details
Published on March 11, 2024 โข 1 min read