Python Enums
An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.
Importing the Module
from enum import Enum
Creating an Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
Accessing Members
print(Color.RED) # Color.RED
print(Color.RED.name) # RED
print(Color.RED.value) # 1
Auto Values
Using auto() allows you to replace the value with an appropriate value automatically.
from enum import Enum, auto
class Color(Enum):
RED = auto()
GREEN = auto()
BLUE = auto()
Iterating
for color in Color:
print(color)
Comparisons
if Color.RED is Color.RED:
print("Identity comparison works")