liveBook · Manning

Enumeration member

As explained in Python How-To

An enumeration member is a named value belonging to an enumeration type and representing one choice in its fixed set.

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

How Python How-To covers it

How deep it goes
Explains member instances, name and value attributes, value lookup, invalid values, and iteration.
Examples
Uses Direction members NORTH, SOUTH, EAST, and WEST with integer and string values.
What it assumes
Assumes familiarity with subclasses and basic classes; distinguishes class attributes from true enumeration members.
What you can do after
Apply it via Python’s enum.Enum to define, inspect, construct, and iterate enumeration members.
How it connects
Connects enumeration members with Enum subclasses, raw values, type checking, API responses, and iteration.

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.