Subclass enum.Enum (class Status(Enum): PENDING = "pending") from Python’s built-in enum module—or enum.StrEnum (Python 3.11+) / enum.IntEnum when members must serialize directly to JSON or compare equal to raw strings/integers—to represent a fixed, type-safe set of symbolic constants with .name, .value, iteration, and match/case exhaustiveness support.

Basic Example

from enum import Enum, StrEnum, auto

# 1. Recommended (general-purpose type-safe Enum):
class OrderStatus(Enum):
    PENDING = "pending"
    SHIPPED = "shipped"
    DELIVERED = "delivered"

status = OrderStatus.SHIPPED
print(status)           # Output: OrderStatus.SHIPPED
print(status.name)      # Output: 'SHIPPED'
print(status.value)     # Output: 'shipped'

# Look up member by value (raises ValueError if invalid) or by name:
parsed = OrderStatus("delivered")
by_name = OrderStatus["PENDING"]
print(parsed is OrderStatus.DELIVERED)  # Output: True

# 2. StrEnum (Python 3.11+) with auto(): values automatically become lowercase member names!
class Role(StrEnum):
    ADMIN = auto()      # Value is 'admin'
    EDITOR = auto()     # Value is 'editor'

print(Role.ADMIN == "admin")            # Output: True (works seamlessly in JSON & f-strings)
print(f"Role: {Role.ADMIN}")            # Output: Role: admin

Key Details & Edge Cases

  • Compare standard Enum members with is (or ==), NEVER against raw values:
    • For a plain Enum, OrderStatus.PENDING == "pending" evaluates to False—only OrderStatus.PENDING is OrderStatus.PENDING (or ==) is True. Use StrEnum (Python 3.11+) or IntEnum only when your enum must interoperate directly with JSON serializers, SQL queries, or external APIs expecting raw str/int values.
  • Duplicate values create silent aliases unless decorated with @enum.unique:
    • If two members share the same value (A = 1; B = 1), Python treats B as an alias for A (MyEnum.B is MyEnum.A is True) and skips B during for member in MyEnum: iteration. Apply @enum.unique above the class to raise ValueError: duplicate values found at import time if duplicate values are accidental.
  • auto() generates different values depending on the base class:
    • Inside Enum or IntEnum, auto() assigns sequential integers starting at 1 (1, 2, 3, ...).
    • Inside StrEnum, auto() assigns the lowercased member name (RED = auto() $\rightarrow$ "red").
    • Inside Flag / IntFlag, auto() assigns powers of two (1, 2, 4, 8, ...) so members can be combined with bitwise operators (Permission.READ | Permission.WRITE and checked with Permission.READ in perms).
  • Adding helper methods and properties to an Enum:
    • Enum classes are full Python classes—you can define @property, @classmethod, and regular methods (using self.value or self.name), and Python automatically ignores callables/methods so they do not become enum members.
  • Exhaustive pattern matching (match / case) and isinstance:
    • Always reference enum members via dot notation in match/case (case OrderStatus.PENDING:)—writing bare case PENDING: treats PENDING as a wildcard capture variable and matches everything!

Comparison of enum Base Classes in Python

Class Inherits From Equal to Raw str / int? JSON-Serializable Out of the Box? Best Used When
enum.Enum (Recommended) Enum No (Status.OK == "ok" is False) No (use .value) Domain states, finite state machines, and strict type safety preventing accidental string/int mixing.
enum.StrEnum (Python 3.11+) str, Enum Yes (Role.ADMIN == "admin" is True) **