Enums are basically a data type that is made up of constants. In order to use enums in Python, we import enum
from the standard library:
from enum import Enum
Enums then can be declared in the following manner:
class State(Enum):
SUCCESS = 'GREEN'
WARNING = 'YELLOW'
DANGER = 'RED'
Enums can then be accessed like so:
print(State.SUCCESS)
The above print statement will return State.SUCCESS
and not GREEN
. We can reach the same state using the following statement:
print(State('GREEN')) # State.SUCCESS
In order to get the value of an enum we do the following:
print(State.SUCCESS.value) # GREEN
All the values of an enum can be listed in the following manner:
list(State) # [<State.SUCCESS: 'GREEN'>, <State.WARNING: 'YELLOW'>, <State.DANGER: 'RED'>]
We can even get the length of an enum:
len(State) # 3