How to type hint Enums in Python

avatar

Borislav Hadzhiev

Fri Jun 17 20221 min read

banner

Photo by Jeremy Bishop

Type hint Enums in Python #

Use the enumeration class to type hint an enum in Python, e.g. def get_value_from_enum(size: Sizes):. You can then access any member of the enum in the body of the function without getting a warning.

main.py
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.

An alternative approach is to use the Literal type to specify that the function argument can be one of the members in the enum.

main.py
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).

Use the search field on my Home Page to filter through my more than 1,000 articles.