Programming Fundamentals › Type Systems
Enum
A type with a fixed set of named values.
Also known as: enumeration, enumerated type, enums
An enum (enumeration) is a type with a fixed set of named values. It replaces loose strings and numbers with choices the program can check.
from enum import Enum
class Status(Enum):
PENDING = "pending"
PAID = "paid"
SHIPPED = "shipped"
order.status = Status.PAID
if order.status == Status.SHIPPED:
...
Status("paid") # Status.PAID, from stored text
Status.PAID.value # "paid"
enum Status { PENDING, PAID, SHIPPED }
enum Status { Pending = "pending", Paid = "paid" }
type Status2 = "pending" | "paid"; // a string union is a common alternative
Why not plain strings or numbers
- No typos.
Status.PADis an error."pad"is a quiet bug. - Clear meaning.
Status.PAIDbeats2(magic numbers). - Autocomplete lists valid options.
- Exhaustiveness. The compiler or linter can warn if a
switchforgets a value (switch).
Practical points
- Store a stable value, not a position. If you save
1for “PAID” and later insert a value in the middle, old data changes meaning. Give each value an explicit, permanent code. - Handle unknown values coming from outside (an API sends a status you don’t know), instead of crashing.
- Adding values is easy. Removing or renaming them can break stored data and other systems.
- Databases can store them as text with a check constraint, a lookup table, or a native enum type, each with trade-offs (DB enums).
- Don’t use an enum for values that change often (a list of countries or products). That’s data, not code.
- For values that carry different data per variant, see discriminated unions.