16. Enumerations
An enum is a type whose values come from a fixed set of named choices. Enums are useful when a value should be one of a small number of valid options, such as status codes, directions, or roles.
16.1. Basic enum
Without an enum, it is easy to scatter string constants throughout a program.
1STATUS_DRAFT = 'draft'
2STATUS_PUBLISHED = 'published'
3STATUS_ARCHIVED = 'archived'
With Enum, the valid choices live in one clear type.
1from enum import Enum
2
3
4class Status(Enum):
5 DRAFT = 'draft'
6 PUBLISHED = 'published'
7 ARCHIVED = 'archived'
8
9
10status = Status.DRAFT
11print(status)
12print(status.value)
16.2. Why enums help
Enums make the set of valid states explicit. That improves readability and reduces bugs caused by typos in plain strings or magic numbers.
16.3. Using StrEnum
In modern Python, StrEnum is often a better fit when the enum values should still behave like strings at boundaries such as JSON or configuration files.
1from enum import StrEnum
2
3
4class Role(StrEnum):
5 ADMIN = 'admin'
6 EDITOR = 'editor'
7 VIEWER = 'viewer'
8
9
10role = Role.ADMIN
11print(role)
12print(role == 'admin')
16.4. Looping over enum values
Enums are iterable, which makes them easy to display in menus or validate user-facing choices.
1from enum import Enum
2
3
4class Direction(Enum):
5 NORTH = 'north'
6 SOUTH = 'south'
7 EAST = 'east'
8 WEST = 'west'
9
10
11for direction in Direction:
12 print(direction.name, direction.value)
16.5. When to use enums
Use enums when the set of choices is stable and meaningful. If you simply need arbitrary user-provided strings, a normal string is still the right tool.
16.6. Exercise
Create an enum named TicketStatus for a bug tracker with the values OPEN, IN_PROGRESS, BLOCKED, and DONE. Then:
create a list of fake tickets using those values
count how many tickets are in each status
print a friendly menu by looping over the enum