← Back to Python, page 3

python-0046 · Medium mid

Use Enum for fixed sets of values and show its common features.

Enum creates a set of named, unique constants. Members compare by identity, can be looked up by value or name, and can be iterated. StrEnum and IntEnum members also behave like strings or integers, which helps with JSON and databases; auto() assigns values automatically.

Full answer
python
from enum import Enum, StrEnum, auto

class Status(StrEnum):
    PENDING = auto()
    SHIPPED = auto()
    CANCELLED = auto()

class Size(Enum):
    S = 1
    M = 2
    L = 3

print(Status.SHIPPED, Status("pending"), Status["CANCELLED"].value)
print(Status.SHIPPED == "shipped", [s.value for s in Status])
print(Size(2), Size.M.name, Size.M is Size(2), Size.M == 2)
try:
    Status("lost")
except ValueError as e:
    print("ValueError:", e)
match Status("shipped"):
    case Status.SHIPPED:
        print("track parcel")

Output:

text
shipped pending cancelled
True ['pending', 'shipped', 'cancelled']
Size.M M True False
ValueError: 'lost' is not a valid Status
track parcel

With StrEnum, auto() produces lowercase names as values, and members compare equal to plain strings, so Status.SHIPPED == 'shipped' is True. Plain Enum members are not equal to their values (Size.M == 2 is False), which prevents accidental mixing. Looking up an unknown value raises ValueError, a cheap way to validate input. Enums work well with match statements. Store .value in databases and JSON, and convert back with Status(value).

python
from enum import Enum, StrEnum, auto

class Status(StrEnum):
    PENDING = auto()
    SHIPPED = auto()
    CANCELLED = auto()

class Size(Enum):
    S = 1
    M = 2
    L = 3

print(Status.SHIPPED, Status("pending"), Status["CANCELLED"].value)
print(Status.SHIPPED == "shipped", [s.value for s in Status])
print(Size(2), Size.M.name, Size.M is Size(2), Size.M == 2)
try:
    Status("lost")
except ValueError as e:
    print("ValueError:", e)
match Status("shipped"):
    case Status.SHIPPED:
        print("track parcel")

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Enums give named unique constants
  • Lookup by value or name
  • StrEnum and IntEnum mix in base types
  • Unknown values raise ValueError
  • Store .value externally

Common mistakes

  • Using bare strings for statuses everywhere
  • Comparing plain Enum members with raw values

Follow-ups

  • What does @enum.unique do?
  • How would you add a method to an Enum?

Tips

  • Show validation by lookup