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
Enummembers withis(or==), NEVER against raw values:- For a plain
Enum,OrderStatus.PENDING == "pending"evaluates toFalse—onlyOrderStatus.PENDING is OrderStatus.PENDING(or==) isTrue. UseStrEnum(Python 3.11+) orIntEnumonly when your enum must interoperate directly with JSON serializers, SQL queries, or external APIs expecting rawstr/intvalues.
- For a plain
- Duplicate values create silent aliases unless decorated with
@enum.unique:- If two members share the same value (
A = 1; B = 1), Python treatsBas an alias forA(MyEnum.B is MyEnum.AisTrue) and skipsBduringfor member in MyEnum:iteration. Apply@enum.uniqueabove the class to raiseValueError: duplicate values foundat import time if duplicate values are accidental.
- If two members share the same value (
auto()generates different values depending on the base class:- Inside
EnumorIntEnum,auto()assigns sequential integers starting at1(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.WRITEand checked withPermission.READ in perms).
- Inside
- Adding helper methods and properties to an
Enum:Enumclasses are full Python classes—you can define@property,, and regular methods (usingself.valueorself.name), and Python automatically ignores callables/methods so they do not become enum members.
- Exhaustive pattern matching (
match/case) andisinstance:- Always reference enum members via dot notation in
match/case(case OrderStatus.PENDING:)—writing barecase PENDING:treatsPENDINGas a wildcard capture variable and matches everything!
- Always reference enum members via dot notation in
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) |
** |
You must log in or register to comment.
