Skip to content

Enums

An enum is a class with a fixed set of named members, such as order states, log levels or HTTP methods. Enums replace “magic strings” and “magic numbers”: a typo becomes an error, and editors can autocomplete the choices.

I want to… Use… Example
name a fixed set of choices class Status(Enum): Status.PAID
members that are real strings StrEnum Method.GET == "GET"
members that are real, ordered ints IntEnum Priority.HIGH > Priority.LOW
combinable on/off options Flag (or IntFlag) Perm.READ | Perm.WRITE
choose values automatically auto() Enum: 1, 2, 3; StrEnum: lowercase name; Flag: 1, 2, 4
look up a member by value Status("paid") ValueError if unknown
look up a member by name Status["PAID"] KeyError if unknown
look up safely Status.__members__.get(name) or try/except ValueError None if unknown
accept messy input (case, spaces) a _missing_ class method Status(" PAID ")
test a value (3.12+) "paid" in Status True
test a member Status.PAID in Status True
get the name and the value .name, .value 'PAID', 'paid'
list all members list(Status), for s in Status definition order, no aliases
count the members len(Status)
map names to members, aliases included Status.__members__ a read-only mapping
compare members is (members are singletons) if s is Status.PAID:
branch on a member match s: / case Status.PAID: dotted names only
add behavior to members methods and properties in the enum Status.PAID.is_final
attach several values to a member a tuple value + __init__ PLANET = (mass, radius)
forbid duplicate values @enum.unique ValueError at class creation
check unique or gap-free values @enum.verify(UNIQUE, CONTINUOUS) ValueError: invalid enum 'C': missing values 2
keep a constant in an enum that is not a member LIMIT = enum.nonmember(10) Status.LIMIT is 10, not in list(Status)
create an enum from a list the functional API Enum("Color", ["RED", "GREEN"])
store in JSON or a database .value, or a StrEnum / IntEnum json.dumps(s.value)
restrict CLI choices choices=[s.value for s in Status] argparse
validate API input an enum field in pydantic status: Status
standard-library enums http.HTTPStatus, http.HTTPMethod, signal.Signals, re.RegexFlag HTTPStatus.NOT_FOUND.value → 404
from enum import Enum, unique
@unique # duplicate values would raise ValueError here
class Status(Enum):
PENDING = "pending"
PAID = "paid"
SHIPPED = "shipped"
CANCELLED = "cancelled"
@property
def is_final(self) -> bool: # behavior lives with the choices
return self in (Status.SHIPPED, Status.CANCELLED)
@classmethod
def open_states(cls) -> list["Status"]:
return [s for s in cls if not s.is_final]
s = Status("paid") # by value
print(s, repr(s), s.name, s.value, Status["PAID"] is s) # by name; singletons
print([m.value for m in Status], len(Status), "paid" in Status, "PAID" in Status)
print(s.is_final, Status.SHIPPED.is_final, [m.name for m in Status.open_states()])
print(s == "paid", s.value == "paid", f"{s}", f"{s.value}")
Output
Status.PAID <Status.PAID: 'paid'> PAID paid True
['pending', 'paid', 'shipped', 'cancelled'] 4 True False
False True ['PENDING', 'PAID']
False True Status.PAID paid
Operation Result Unknown input
Status("paid") member by value ValueError: 'x' is not a valid Status
Status["PAID"] member by name KeyError: 'x'
getattr(Status, "PAID") member by name AttributeError
"paid" in Status (3.12+) is it a value? False
Status.PAID.name, .value 'PAID', 'paid' —
list(Status) members in definition order, aliases skipped —
Status.__members__ name → member, aliases included —
Status.PAID is Status("paid") True: one object per member —
Status.PAID = "x" AttributeError: members are read-only —
Status.PAID < Status.SHIPPED TypeError for a plain Enum use IntEnum or define __lt__

A second name with an existing value is an alias: DONE = "shipped" in the class body makes Status.DONE is Status.SHIPPED. @unique forbids aliases.

import json
from enum import Flag, IntEnum, StrEnum, auto
class Method(StrEnum):
GET = auto() # auto() in a StrEnum: the lowercase name
POST = auto()
class Priority(IntEnum):
LOW = 1
NORMAL = 2
HIGH = 3
class Perm(Flag):
READ = auto() # 1
WRITE = auto() # 2
DELETE = auto() # 4
ADMIN = READ | WRITE | DELETE # a named combination
print(Method.GET, Method.GET == "get", Method.POST.upper(), json.dumps([Method.GET]))
print(Priority.HIGH > Priority.LOW, Priority.NORMAL + 1, max(Priority).name)
print(sorted([Priority.HIGH, Priority.LOW]), Priority(2).name, f"{Priority.LOW}")
user = Perm.READ | Perm.WRITE
print(user, Perm.WRITE in user, Perm.DELETE in user, Perm.READ in Perm.ADMIN)
print(user & ~Perm.WRITE, bool(Perm(0)), [p.name for p in user], Perm.ADMIN.value)
Output
get True POST ["get"]
True 3 HIGH
[<Priority.LOW: 1>, <Priority.HIGH: 3>] NORMAL 1
Perm.READ|WRITE True False True
Perm.READ False ['READ', 'WRITE'] 7
Enum StrEnum (3.11+) IntEnum Flag IntFlag
Member is a member only str int member, combinable int, combinable
member == value False True True False True
< between members TypeError as strings as ints TypeError as ints
str(member) / f-string Status.PAID get (the value) 1 (the value) Perm.READ 1
json.dumps(member) TypeError the value the value TypeError the value
auto() values 1, 2, 3 lowercase name 1, 2, 3 1, 2, 4, 8 1, 2, 4, 8
Use for states, kinds, modes HTTP methods, config keys, DB codes priorities, levels, status codes permissions, feature sets OS flags, re flags
Stdlib example uuid.SafeUUID http.HTTPMethod http.HTTPStatus your own permission sets re.RegexFlag, ssl.VerifyFlags
Code Value
A = auto() in Enum / IntEnum 1, 2, 3, … (highest int value so far + 1, on 3.13+)
A = auto() in StrEnum "a" (lowercase name)
A = auto() in Flag / IntFlag 1, 2, 4, 8, …
_generate_next_value_(name, start, count, last_values) your rule for auto(); define it first in the class (a static method)
A = "text" any value; mix literals with auto() only when they are ints (Enum, IntEnum) or strings (StrEnum)
MARS = (6.4e23, 3.39e6) + def __init__(self, mass, radius) several attributes per member; .value is the tuple
from enum import Enum
class Plan(Enum):
FREE = ("free", 0)
PRO = ("pro", 1200) # (code, price in cents)
def __init__(self, code: str, cents: int) -> None: # runs once per member
self.code = code
self.cents = cents
@property
def label(self) -> str:
return f"{self.name.title()} ({self.cents / 100:.2f} USD/month)"
print(Plan.PRO.code, Plan.PRO.cents, Plan.PRO.label, Plan(("free", 0)).name)
Output
pro 1200 Pro (12.00 USD/month) FREE
from enum import StrEnum
class Env(StrEnum):
DEV = "dev"
STAGING = "staging"
PROD = "prod"
@classmethod
def _missing_(cls, value: object) -> "Env | None": # called when lookup fails
aliases = {"development": "dev", "production": "prod"}
if isinstance(value, str):
key = value.strip().lower()
key = aliases.get(key, key)
for member in cls:
if member.value == key:
return member
return None # None: Python raises the usual ValueError
print(Env(" PROD "), Env("Development"), Env("staging"))
try:
Env("qa")
except ValueError as err:
print(err)
Output
prod dev staging
'qa' is not a valid Env

_missing_ runs only for value lookup, Env(...). Name lookup, Env["..."], never calls it.

from enum import Enum, auto
class Shape(Enum):
CIRCLE = auto()
SQUARE = auto()
TRIANGLE = auto()
def corners(shape: Shape) -> int:
match shape:
case Shape.CIRCLE: # a dotted name: a value pattern, compared with ==
return 0
case Shape.SQUARE:
return 4
case Shape.TRIANGLE:
return 3
case _: # fail loudly if a member is added and not handled
raise ValueError(f"unhandled {shape!r}")
def kind(value: object) -> str:
match value:
case Shape.CIRCLE | Shape.SQUARE: # OR pattern
return "regular"
case Shape(): # class pattern: any other Shape member
return "other shape"
case _:
return "not a shape"
print([corners(s) for s in Shape], kind(Shape.SQUARE), kind(Shape.TRIANGLE), kind(3))
Output
[0, 4, 3] regular other shape not a shape
Pattern Means
case Shape.CIRCLE: value pattern: == Shape.CIRCLE
case CIRCLE: capture pattern: binds any value to the name CIRCLE and always matches
case Shape.CIRCLE | Shape.SQUARE: either member
case Shape(): any member of Shape
case "get": on a StrEnum member matches, because the member equals the string

mypy and pyright warn when a match on an enum misses a member, if you end with case _: assert_never(shape) (from typing import assert_never).

Task Code
to JSON json.dumps({"status": s.value}); a StrEnum / IntEnum works directly
from JSON Status(data["status"])
from a config or env var Env(os.environ.get("APP_ENV", "dev"))
an argparse option parser.add_argument("--env", type=Env, choices=list(Env))
a pydantic field status: Status; the input "paid" becomes Status.PAID
a database column store .value; SQLAlchemy has Enum(Status)
a dataclass field status: Status = Status.PENDING; asdict() keeps the member
a dict keyed by member {Status.PAID: "green", Status.CANCELLED: "red"}; members are hashable
a pandas column df["status"].map(lambda v: Status(v).name), or a categorical with the values
import json
from enum import Enum
class Color(Enum):
RED = "red"
BLUE = "blue"
Level = Enum("Level", ["DEBUG", "INFO", "ERROR"]) # functional API: values 1, 2, 3
payload = json.dumps({"color": Color.RED.value})
print(payload, Color(json.loads(payload)["color"]), Level.INFO.value, Level(3).name)
try:
json.dumps({"color": Color.RED})
except TypeError as err:
print(err)
Output
{"color": "red"} Color.RED 2 ERROR
Object of type Color is not JSON serializable
  • A plain Enum member is not its value. Symptom: Status.PAID == "paid" is False. Fix: compare with .value, convert input with Status(value), or use StrEnum.
  • StrEnum and IntEnum equal their values. Symptom: mix-ups such as Priority.HIGH == 3 and Priority.HIGH + 1 pass silently. Fix: use a plain Enum when members must not act like numbers or strings.
  • str() differs by kind. Symptom: an f-string shows Status.PAID for Enum but paid for StrEnum and 1 for IntEnum. Fix: write .value or .name explicitly in output.
  • auto() in a StrEnum uses the lowercase name. Symptom: MONTH_TO_MONTH = auto() gives "month_to_month", not "month-to-month". Fix: write the value explicitly when it must match external data.
  • Capture pattern in match. Symptom: case PAID: binds any value to the name PAID and always matches: a SyntaxError when other cases follow, a silent catch-all when it is last. Fix: write case Status.PAID:.
  • json.dumps() of a plain Enum. Symptom: TypeError: Object of type Color is not JSON serializable. Fix: dump .value, or use StrEnum.
  • Aliases hide in iteration. Symptom: list(Status) misses a name you defined. Fix: it is an alias of an earlier member; use __members__ or @unique.
  • auto() after a non-int literal. Symptom: A = "x" then B = auto() in a plain Enum raises TypeError: unable to increment 'x'. Fix: give every member an explicit value, or use auto() for all of them.
  • Value vs name lookup. Symptom: Status("PAID") raises ValueError. Fix: Status["PAID"] looks up names; Status("paid") looks up values.
  • Ordering a plain Enum. Symptom: TypeError: '<' not supported between instances of 'Status' and 'Status'. Fix: IntEnum, or sorted(members, key=lambda m: m.value).
  • Mutable or float values. Symptom: a list value cannot be looked up by value quickly, and float values compare inexactly. Fix: use strings, ints or tuples.
  • Subclassing an enum with members. Symptom: TypeError: <enum 'Sub'> cannot extend <enum 'Status'>. Fix: only enums without members can be subclassed; share behavior with a base enum that has no members.