Need a function to accept one of a few directions? Strings such as "north" work, but a caller might supply "North" and get rejected. An enumeration gives related choices named members of one type, making the expected input clearer. section 9.1
Define and use an Enum
from enum import Enum class Direction(Enum): NORTH = 0 SOUTH = 1 EAST = 2 WEST = 3 north = Direction.NORTH print(isinstance(north, Direction)) # True print(north.name, north.value) # NORTH 0 print(Direction(2)) # Direction.EAST print(list(Direction)) # [<Direction.NORTH: 0>, <Direction.SOUTH: 1>, # <Direction.EAST: 2>, <Direction.WEST: 3>] Subclass Enum and put each member on its own line for readability. Members are instances of Direction; constructing Direction from a defined value retrieves its member, while an undefined value raises ValueError. section 9.1.2 section 9.1.3
A regular class containing NORTH = 0 and similar attributes is not equivalent: those attributes are integers, not instances of the class, and the class cannot be iterated over its choices. Enum supports both typed members and iteration; membership checks can also help validate an input. section 9.1.1 section 9.6
Listing 9.2 Adding a custom method
class Direction(Enum):
NORTH = 0
SOUTH = 1
EAST = 2
WEST = 3
def __str__(self):
return self.name.lower()
def move_to(direction: Direction, distance: float):
if direction in Direction:
message = f"Go to the {direction} for {distance} miles"
else:
message = "Wrong input for direction"
print(message)
move_to(Direction.NORTH, 3)
# output: Go to the north for 3 miles
A custom __str__ method makes a direction member display as human-readable lowercase text when formatted in a message. section 9.1.4
Values need not be consecutive integers: they can be other integers or strings. For task statuses that must be sortable by integer value, IntEnum is used; a separate Enum represents the choice between CSV and SQLite storage. Do not confuse an Enum with enumerate(): enumerate() pairs iterable items with counters rather than defining a category of named members. section 9.1.2 section 14.2.2 section 5.3.1






















