Sometimes a variable can only take a few fixed values: the state of a task, a day of the week, a color. Using loose numbers or texts is error-prone (was it "done" or "finished"?). An enumeration groups those named constants.
Defining an enumeration
from enum import Enum
class State(Enum):
PENDING = 1
IN_PROGRESS = 2
DONE = 3
print(State.IN_PROGRESS) # State.IN_PROGRESS
print(State.IN_PROGRESS.name) # IN_PROGRESS
print(State.IN_PROGRESS.value) # 2
Each member has a name (name) and a value (value). By convention, the names are in UPPER CASE.
Looking up a member
| Form | Looks up by | If it does not exist |
|---|---|---|
State(2) | Value | ValueError |
State["IN_PROGRESS"] | Name | KeyError |
print(State(2)) # State.IN_PROGRESS
print(State["DONE"]) # State.DONE
try:
State(9)
except ValueError:
print("Unknown state") # Unknown state
Practice with States with Enum.
Looping and comparing
An enumeration is iterable, in the order in which it was defined. Members are compared with == or with is:
for state in State:
print(state.name, state.value)
# PENDING 1
# IN_PROGRESS 2
# DONE 3
current = State.PENDING
print(current == State.PENDING) # True
print(current is State.DONE) # False
print(list(State)[0]) # State.PENDING
Careful: a member is not equal to its value: State.PENDING == 1 is False. Practice with Next color.
Automatic values with auto()
If you do not care about the values, auto() numbers them for you starting at 1:
from enum import Enum, auto
class Color(Enum):
RED = auto()
GREEN = auto()
BLUE = auto()
print(Color.BLUE.value) # 3
Methods and text values
Enumerations are classes, so they can have methods. The values can also be texts:
class TrafficLight(Enum):
RED = "red"
AMBER = "amber"
GREEN = "green"
def can_go(self) -> bool:
return self is TrafficLight.GREEN
print(TrafficLight.GREEN.can_go()) # True
print(TrafficLight("amber")) # TrafficLight.AMBER
IntEnum: enumerations that are numbers
The members of an IntEnum behave like integers, so they can be compared with < and >= and operated on:
from enum import IntEnum
class Level(IntEnum):
DEBUG = 10
INFO = 20
WARNING = 30
ERROR = 40
print(Level.ERROR > Level.INFO) # True
print(Level.WARNING == 30) # True
print(sorted([Level.ERROR, Level.DEBUG, Level.WARNING]))
# [<Level.DEBUG: 10>, <Level.WARNING: 30>, <Level.ERROR: 40>]
It is perfect for levels, priorities or sizes. Practice with Log level filter.
Why use enumerations?
- They avoid typos:
State.DOENgives an immediate error;"doen"would go unnoticed. - They document the possible values in a single place.
- The editor autocompletes the members.
- Members can be used in
if,match, dictionaries and dataclasses.