enum provides symbolic named constants that can be compared, iterated, and serialized. from enum import Enum, IntEnum, StrEnum, Flag, IntFlag, auto, unique. Enum: class Color(Enum): RED=1; GREEN=2; BLUE=3. Access: Color.RED; Color["RED"]; Color(1). Name/value: Color.RED.name → "RED"; Color.RED.value → 1. Iterate: list(Color). Membership: Color.RED in Color. IntEnum: class Status(IntEnum): OK=200; NOT_FOUND=404 — works as int in comparisons. StrEnum: class Dir(StrEnum): NORTH="north" (Python 3.11+) — works as str. auto: class Priority(Enum): LOW=auto(); MEDIUM=auto(); HIGH=auto() — auto sequential values. Flag: class Perm(Flag): READ=auto(); WRITE=auto(); EXEC=auto(); RWX=READ|WRITE|EXEC. IntFlag: same but int-compatible. unique: @unique class X(Enum): A=1; B=1 — raises ValueError. missing: classmethod for unknown value handling. generate_next_value: customize auto. aliases: B=1; C=1 — C is alias for B. Functional API: Status = Enum("Status",["OPEN","CLOSED"]). mixin: class Color(str, Enum): RED="red" — StrEnum pattern pre-3.11. @property: add computed attributes to members. list(Perm) — only canonical members. Perm.READ|Perm.WRITE — compound flag. Perm.READ in Perm.RWX — membership test. Claude Code generates HTTP status enums, state machines, permission flags, and config constant registries.
CLAUDE.md for enum
## enum Stack
- Stdlib: from enum import Enum, IntEnum, StrEnum, Flag, IntFlag, auto, unique
- Basic: class Status(Enum): OPEN=auto() | CLOSED=auto()
- Int: class HTTPStatus(IntEnum): OK=200 | NOT_FOUND=404 — use when int comparison needed
- Str: class Direction(StrEnum): NORTH="north" (Python 3.11+)
- Flag: class Permission(Flag): READ=auto() | WRITE=auto() — combine with |
- Parse: Status("open") | Status["OPEN"] | Status._missing_(val) for lenient parsing
enum Constant and State Machine Pipeline
# app/enums.py — Enum, IntEnum, StrEnum, Flag, auto, state machine, HTTP status
from __future__ import annotations
from enum import (
Enum,
Flag,
IntEnum,
IntFlag,
auto,
unique,
)
from typing import Any, Iterator
# ─────────────────────────────────────────────────────────────────────────────
# 1. Basic enums
# ─────────────────────────────────────────────────────────────────────────────
@unique
class Color(Enum):
"""
RGB color constants.
Example:
c = Color.RED
print(c.name, c.value) # RED 1
print(Color["RED"]) # Color.RED
print(Color(2)) # Color.GREEN
print(list(Color)) # [Color.RED, Color.GREEN, Color.BLUE]
"""
RED = 1
GREEN = 2
BLUE = 3
def to_hex(self) -> str:
mapping = {1: "#FF0000", 2: "#00FF00", 3: "#0000FF"}
return mapping[self.value]
@classmethod
def from_hex(cls, hex_code: str) -> Color:
mapping = {"#ff0000": cls.RED, "#00ff00": cls.GREEN, "#0000ff": cls.BLUE}
result = mapping.get(hex_code.lower())
if result is None:
raise ValueError(f"Unknown hex color: {hex_code!r}")
return result
class Priority(Enum):
"""
Task priority using auto() values.
Example:
p = Priority.HIGH
sorted_tasks = sorted(tasks, key=lambda t: t.priority.value)
"""
LOW = auto() # 1
MEDIUM = auto() # 2
HIGH = auto() # 3
URGENT = auto() # 4
def __lt__(self, other: Priority) -> bool:
return self.value < other.value
# ─────────────────────────────────────────────────────────────────────────────
# 2. IntEnum — integer-compatible
# ─────────────────────────────────────────────────────────────────────────────
class HTTPStatus(IntEnum):
"""
Common HTTP status codes. Inherits int so it works wherever int is expected.
Example:
status = HTTPStatus.OK
assert status == 200 # int comparison works
assert status < 300 # ordering works
assert HTTPStatus(404) == HTTPStatus.NOT_FOUND
assert HTTPStatus.OK.phrase # "OK"
"""
# 2xx
OK = 200
CREATED = 201
ACCEPTED = 202
NO_CONTENT = 204
# 3xx
MOVED_PERMANENTLY = 301
NOT_MODIFIED = 304
# 4xx
BAD_REQUEST = 400
UNAUTHORIZED = 401
FORBIDDEN = 403
NOT_FOUND = 404
METHOD_NOT_ALLOWED = 405
CONFLICT = 409
UNPROCESSABLE_ENTITY = 422
TOO_MANY_REQUESTS = 429
# 5xx
INTERNAL_SERVER_ERROR = 500
BAD_GATEWAY = 502
SERVICE_UNAVAILABLE = 503
@property
def phrase(self) -> str:
return self.name.replace("_", " ").title()
@property
def is_success(self) -> bool:
return 200 <= self.value < 300
@property
def is_client_error(self) -> bool:
return 400 <= self.value < 500
@property
def is_server_error(self) -> bool:
return 500 <= self.value < 600
@classmethod
def _missing_(cls, value: object) -> HTTPStatus | None:
"""Return None for unknown status codes instead of raising ValueError."""
return None
# ─────────────────────────────────────────────────────────────────────────────
# 3. StrEnum-style (str mixin, Python 3.10 compatible)
# ─────────────────────────────────────────────────────────────────────────────
class Environment(str, Enum):
"""
Deployment environment — works as a string everywhere.
Example:
env = Environment.PRODUCTION
assert env == "production" # str comparison
assert env.upper() == "PRODUCTION" # str methods
print(f"Deploying to {env}") # "Deploying to production"
"""
DEVELOPMENT = "development"
STAGING = "staging"
PRODUCTION = "production"
TEST = "test"
@property
def is_prod_like(self) -> bool:
return self in (Environment.STAGING, Environment.PRODUCTION)
@property
def log_level(self) -> str:
return "DEBUG" if self == Environment.DEVELOPMENT else "INFO"
@classmethod
def _missing_(cls, value: object) -> Environment | None:
if isinstance(value, str):
for member in cls:
if member.value == value.lower():
return member
return None
# ─────────────────────────────────────────────────────────────────────────────
# 4. Flag — bitmask combinations
# ─────────────────────────────────────────────────────────────────────────────
class Permission(Flag):
"""
File/resource permissions as composable flags.
Example:
perm = Permission.READ | Permission.WRITE
assert Permission.READ in perm
assert Permission.EXEC not in perm
print(perm) # Permission.READ|WRITE
rw = Permission.RW
assert rw == (Permission.READ | Permission.WRITE)
"""
NONE = 0
READ = auto()
WRITE = auto()
EXEC = auto()
# Compound aliases
RW = READ | WRITE
RX = READ | EXEC
RWX = READ | WRITE | EXEC
def allows(self, required: Permission) -> bool:
return (self & required) == required
@classmethod
def from_octal(cls, octal: int) -> Permission:
"""
Parse Unix octal permission: 7=RWX, 6=RW, 5=RX, 4=R, 1=X.
Example:
Permission.from_octal(6) # Permission.READ|WRITE
"""
perm = cls.NONE
if octal & 4:
perm |= cls.READ
if octal & 2:
perm |= cls.WRITE
if octal & 1:
perm |= cls.EXEC
return perm
def to_octal(self) -> int:
val = 0
if Permission.READ in self:
val += 4
if Permission.WRITE in self:
val += 2
if Permission.EXEC in self:
val += 1
return val
class LogLevel(IntFlag):
"""
Log level flags usable as integer bitmask.
Example:
active = LogLevel.INFO | LogLevel.ERROR
assert LogLevel.INFO in active
assert LogLevel.DEBUG not in active
"""
NOTSET = 0
DEBUG = 10
INFO = 20
WARNING = 30
ERROR = 40
CRITICAL = 50
# ─────────────────────────────────────────────────────────────────────────────
# 5. State machine
# ─────────────────────────────────────────────────────────────────────────────
class OrderStatus(Enum):
"""
Order lifecycle states with allowed transitions.
Example:
order = OrderStatus.PENDING
order = order.transition_to(OrderStatus.CONFIRMED)
order = order.transition_to(OrderStatus.SHIPPED)
# order.transition_to(OrderStatus.PENDING) → raises ValueError
"""
PENDING = "pending"
CONFIRMED = "confirmed"
SHIPPED = "shipped"
DELIVERED = "delivered"
CANCELLED = "cancelled"
REFUNDED = "refunded"
# Allowed (from → set_of_tos)
_TRANSITIONS: dict = {} # populated below
def can_transition_to(self, next_state: OrderStatus) -> bool:
allowed = {
OrderStatus.PENDING: {OrderStatus.CONFIRMED, OrderStatus.CANCELLED},
OrderStatus.CONFIRMED: {OrderStatus.SHIPPED, OrderStatus.CANCELLED},
OrderStatus.SHIPPED: {OrderStatus.DELIVERED, OrderStatus.CANCELLED},
OrderStatus.DELIVERED: {OrderStatus.REFUNDED},
OrderStatus.CANCELLED: set(),
OrderStatus.REFUNDED: set(),
}
return next_state in allowed.get(self, set())
def transition_to(self, next_state: OrderStatus) -> OrderStatus:
if not self.can_transition_to(next_state):
raise ValueError(
f"Invalid transition: {self.value!r} → {next_state.value!r}"
)
return next_state
@property
def is_terminal(self) -> bool:
return self in (OrderStatus.DELIVERED, OrderStatus.CANCELLED, OrderStatus.REFUNDED)
@property
def label(self) -> str:
return self.value.replace("_", " ").capitalize()
# ─────────────────────────────────────────────────────────────────────────────
# 6. Lenient parsing helper
# ─────────────────────────────────────────────────────────────────────────────
def parse_enum(cls: type[Enum], value: Any, default=None) -> Any:
"""
Parse a string or int into an enum member; return default if not found.
Example:
parse_enum(Color, "RED") # Color.RED
parse_enum(Color, 1) # Color.RED
parse_enum(Color, "X", default=Color.BLUE) # Color.BLUE
"""
with suppress_value_errors():
if isinstance(value, cls):
return value
try:
return cls(value)
except (ValueError, KeyError):
pass
if isinstance(value, str):
try:
return cls[value.upper()]
except KeyError:
pass
return default
from contextlib import suppress as suppress_value_errors # noqa: E402
def enum_choices(cls: type[Enum]) -> list[str]:
"""
Return list of all member names — useful for argparse/click choices.
Example:
parser.add_argument("--env", choices=enum_choices(Environment))
"""
return [m.name for m in cls]
def enum_values(cls: type[Enum]) -> list[Any]:
"""Return list of all member values."""
return [m.value for m in cls]
# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
print("=== enum demo ===")
print("\n--- Color ---")
for c in Color:
print(f" {c.name:8s} value={c.value} hex={c.to_hex()}")
print(f" Color['RED'] = {Color['RED']}")
print(f" Color(2) = {Color(2)}")
print("\n--- Priority ---")
tasks = [(Priority.HIGH,"Task A"),(Priority.LOW,"Task B"),(Priority.MEDIUM,"Task C")]
for p, name in sorted(tasks, key=lambda t: t[0]):
print(f" {p.name}: {name}")
print("\n--- HTTPStatus ---")
for code in [200, 404, 500]:
s = HTTPStatus(code)
print(f" {s.value} {s.phrase:25s} success={s.is_success}")
print(f" missing (999): {HTTPStatus._missing_(999)}")
print("\n--- Environment (StrEnum mixin) ---")
env = Environment.PRODUCTION
print(f" is str: {isinstance(env, str)}")
print(f" == 'production': {env == 'production'}")
print(f" .upper(): {env.upper()}")
print(f" is_prod_like: {env.is_prod_like}")
print(f" _missing_('staging'): {Environment._missing_('staging')}")
print("\n--- Permission (Flag) ---")
perm = Permission.READ | Permission.WRITE
print(f" perm={perm}")
print(f" READ in perm: {Permission.READ in perm}")
print(f" EXEC in perm: {Permission.EXEC in perm}")
print(f" allows(RW): {perm.allows(Permission.RW)}")
print(f" from_octal(7): {Permission.from_octal(7)}")
print(f" RWX.to_octal(): {Permission.RWX.to_octal()}")
print("\n--- OrderStatus (state machine) ---")
order = OrderStatus.PENDING
for next_s in [OrderStatus.CONFIRMED, OrderStatus.SHIPPED, OrderStatus.DELIVERED]:
order = order.transition_to(next_s)
print(f" → {order.label} terminal={order.is_terminal}")
try:
order.transition_to(OrderStatus.PENDING)
except ValueError as e:
print(f" invalid: {e}")
print("\n--- parse_enum ---")
print(f" parse_enum(Color,'RED') = {parse_enum(Color, 'RED')}")
print(f" parse_enum(Color, 2) = {parse_enum(Color, 2)}")
print(f" parse_enum(Color,'X') = {parse_enum(Color, 'X')}")
print(f" choices: {enum_choices(Environment)}")
print("\n=== done ===")
For the aenum alternative — aenum (PyPI; “Advanced Enumerations”) extends stdlib enum with MultiValueEnum (multiple values per member), NoAlias (allow value duplicates without aliases), extend_enum (add members to an existing enum), NamedConstant, and NamedTuple integration; Python’s stdlib enum covers the common 95% of use cases and is always available — use aenum when you need multi-value members, mixin-heavy enum hierarchies, or runtime extend_enum, stdlib enum for all standard constant, flag, and state-machine modeling. For the strenum alternative — strenum (PyPI) provides a StrEnum backport for Python versions below 3.11 where enum.StrEnum does not exist; on Python 3.11+ from enum import StrEnum is stdlib; the str, Enum mixin pattern works on all Python versions — use the str, Enum mixin or strenum backport for 3.10 and below, from enum import StrEnum on Python 3.11+. The Claude Skills 360 bundle includes enum skill sets covering Color/Priority basic enums with auto(), HTTPStatus IntEnum with property methods and missing, Environment StrEnum-style mixin, Permission/LogLevel Flag bitmask, OrderStatus state machine with transition guards, and parse_enum()/enum_choices() parsing helpers. Start with the free tier to try symbolic constants and enum state machine code generation.