How can a fixed choice such as a direction become a real, type-safe value? Define an enumeration by subclassing Python’s Enum class. Each named member becomes a predefined instance of that enumeration rather than an ordinary class attribute. section 9.1.1 section 9.1.2
Listing 9.1 Implementing an enumeration class
from enum import Enum class Direction(Enum): NORTH = 0 SOUTH = 1 EAST = 2 WEST = 3
A readable one-member-per-line definition groups related choices and assigns each member a raw value. section 9.1.2
Once defined, an enumeration member supports several practical operations:
- Check its type: each member is an instance of the enumeration class, so Direction.NORTH has type Direction. section 9.1.3
- Inspect name and value: NORTH is the member name, while 0 is its associated raw value. section 9.1.3
- Convert a known raw value into its member: Direction(2) produces Direction.EAST; an undefined value raises ValueError. section 9.1.3
- Iterate over Direction to obtain all defined members in their declaration order. section 9.1.3
Turning an API value into a direction
direction_value = 2 direction = Direction(direction_value) print(direction) # output: Direction.EAST section 9.1.3
