liveBook · Manning

Enum

As explained in Python How-To

Enumeration is the technique of associating each item in a set of related concepts with a distinct named member of a common category.

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

How Python How-To covers it

How deep it goes
Works through Enum construction, member lookup, attributes, iteration, and custom string behavior; contrasts regular class attributes with true members.
Examples
Uses compass directions, a movement function, sortable task statuses, and CSV-versus-SQLite database choices.
What it assumes
Assumes familiarity with custom classes and subclassing, while demonstrating how to create and use an enumeration class.
What you can do after
Build it from scratch by subclassing Enum, then use members for typed choices, value lookup, iteration, and readable output.
How it connects
Connects enumerations to subclassing, type hints, iteration, membership checking, special methods, and IntEnum.

Also explained in

Compare how 23 books explain enum →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.