How to type hint Enums in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
1 min

banner

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

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

type hint enums in python

The code for this article is available on GitHub

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.

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

using literal type instead

The code for this article is available on GitHub

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

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev