How to type hint Enums in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Photo from Unsplash

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

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.