Last updated: Apr 8, 2024
Reading timeยท1 min
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.
Literal
type insteadAn 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).
You can learn more about the related topics by checking out the following tutorials: