Python Enum Explained: auto, IntEnum, StrEnum, Flag and Best Practices
A Python enum gives a fixed set of named values a proper type, so typos fail loudly and code reads clearly. Learn how to define and look up members, when to use auto, IntEnum, StrEnum and Flag, aliases and the unique decorator, members with extra data, JSON, match statements and the traps that catch people, all tested.
- A Python enum defines a closed set of named constants:
Status.PAIDinstead of the bare string"paid". - Plain
Enummembers are not equal to their values:Status.PAID == "paid"is False.IntEnumandStrEnumchange that. Status("shipped")looks up by value and raisesValueErrorfor unknown values, which makes validation free.json.dumpsfails on plain enum members; serialise.valueor useStrEnum.
Order statuses, user roles, priority levels, payment methods: every codebase has small sets of allowed values. Storing them as plain strings or numbers works until someone types "shiped", compares against "Paid", or passes 4 where only 1 to 3 make sense. A Python enum turns those loose constants into a real type that your editor can autocomplete, your type checker can verify and your code can validate in one line.
All examples ran on Python 3.13.6 and the output is shown as printed. StrEnum needs Python 3.11 or newer; everything else works from 3.6 onwards. For related modelling tools, see our Python dataclasses guide.
Why use an enum instead of strings?
- Typos fail immediately:
Status.SHIPEDraisesAttributeError, while"shiped"silently never matches. - One source of truth: the set of allowed values lives in one class, so listing them for a dropdown or validating input is trivial.
- Readable and searchable:
if order.status is Status.REFUNDEDsays exactly what it means, and you can find every use with a search. - Tooling: editors autocomplete members, and type hints like
def ship(s: Status)let checkers catch wrong arguments.
Defining an enum
from enum import Enum
class Status(Enum):
PENDING = "pending"
PAID = "paid"
SHIPPED = "shipped"
REFUNDED = "refunded"
print(Status.PAID) # Status.PAID
print(repr(Status.PAID)) # <Status.PAID: 'paid'>
print(Status.PAID.name) # PAID
print(Status.PAID.value) # paid
Each member has a name (the identifier) and a value (what you assigned). By convention names are uppercase, because members are constants. Members are created once, when the class is defined, and they are singletons: there is exactly one Status.PAID object in the program.
Looking up and listing members
Status("shipped") # Status.SHIPPED (by value)
Status["REFUNDED"] # Status.REFUNDED (by name)
[s.name for s in Status] # ['PENDING', 'PAID', 'SHIPPED', 'REFUNDED']
len(Status) # 4
Status("lost")
# ValueError: 'lost' is not a valid Status
Calling the class with a value converts raw input, such as a string from a form or an API, into a member, and invalid values raise ValueError straight away. That one line replaces a hand-written if value not in ALLOWED check. Iteration follows definition order, so building a list of choices for a UI is a one-liner.
Comparison rules: identity, not strings
Status.PAID is Status("paid") # True
Status.PAID == "paid" # False
Status.PAID = "x"
# AttributeError: cannot reassign member 'PAID'
Because members are singletons, compare them with is (or ==, which works the same here). The surprise for many developers is the second line: a plain Enum member never equals its raw value. That is deliberate, it prevents accidental mixing of types, but it means code like if order.status == "paid" silently becomes always False after you switch to enums. Members are also read-only, so nobody can change Status.PAID at runtime.
auto(): let Python pick the values
from enum import auto
class Step(Enum):
DRAFT = auto()
REVIEW = auto()
DONE = auto()
[(s.name, s.value) for s in Step]
# [('DRAFT', 1), ('REVIEW', 2), ('DONE', 3)]
When the values do not matter, only the names, auto() assigns them for you, starting at 1. Avoid it when values are stored in a database or sent over an API, because inserting a new member in the middle would renumber the ones after it and silently change their stored meaning.
IntEnum: members that behave like integers
from enum import IntEnum
class Priority(IntEnum):
LOW = 1
MEDIUM = 2
HIGH = 3
Priority.HIGH > Priority.LOW # True
Priority.HIGH == 3 # True
sorted([Priority.HIGH, Priority.LOW]) # [<Priority.LOW: 1>, <Priority.HIGH: 3>]
IntEnum members are real integers, so they compare and sort numerically and equal their values. Use it for ordered levels, HTTP-like codes or values that must interoperate with code expecting ints. The trade-off is weaker type safety: Priority.HIGH + 1 is 4, and any integer comparison works, so mix-ups are not caught.
StrEnum: members that behave like strings
from enum import StrEnum
class Color(StrEnum):
RED = auto()
GREEN = auto()
print(Color.RED) # red
Color.RED == "red" # True
Color.RED.upper() # 'RED'
In a StrEnum, auto() produces the lowercase member name, and members are genuine strings: they compare equal to text, support string methods and print as their value. This is the most convenient choice for values that travel as text, such as JSON fields, query parameters and database columns.
Flag: combinable options
from enum import Flag
class Perm(Flag):
READ = auto()
WRITE = auto()
DELETE = auto()
rw = Perm.READ | Perm.WRITE
print(rw) # Perm.READ|WRITE
Perm.WRITE in rw # True
Perm.DELETE in rw # False
[p.name for p in rw] # ['READ', 'WRITE']
A Flag enum gives each member a separate bit, so members combine with | into sets of options and you test membership with in. It suits permissions, feature toggles and file modes, and it stores compactly as a single integer.
Aliases and the unique decorator
class Alias(Enum):
ACTIVE = 1
ENABLED = 1
Alias.ENABLED # Alias.ACTIVE
Alias.ENABLED is Alias.ACTIVE # True
list(Alias) # [<Alias.ACTIVE: 1>]
from enum import unique
@unique
class Bad(Enum):
A = 1
B = 1
# ValueError: duplicate values found in <enum 'Bad'>: B -> A
Two names with the same value make the second an alias of the first: it is the same member, and iteration skips it. Aliases are handy for renaming a member while keeping the old name working. When duplicates would be a bug, add @unique and Python refuses to create the class.
Members with extra data and methods
class Plan(Enum):
FREE = (0, 1)
PRO = (12, 10)
def __init__(self, price, seats):
self.price, self.seats = price, seats
@property
def per_seat(self):
return self.price / self.seats
Plan.PRO.price, Plan.PRO.seats, Plan.PRO.per_seat # (12, 10, 1.2)
Enums are classes, so members can carry several attributes and expose methods and properties. Keeping a plan’s price and seat count next to its name avoids parallel dictionaries that drift out of sync. Keep this to small, fixed data; anything that changes often belongs in a database. See our classes and objects guide for the class mechanics.
Tip: add a classmethod such as from_label to map messy external input (different spellings or cases) onto members in one tested place.
Enums with JSON and databases
json.dumps({"status": Status.PAID})
# TypeError: Object of type Status is not JSON serializable
json.dumps({"status": Status.PAID.value}) # '{"status": "paid"}'
json.dumps({"c": Color.RED}) # '{"c": "red"}' (StrEnum works)
The standard json module does not know plain enums. Serialise .value when writing and convert back with Status(value) when reading, or use StrEnum or IntEnum, which serialise as their underlying type automatically. The same pattern applies to databases: store the value (a short string is clearest), and enforce it with a CHECK constraint so bad data cannot sneak in from other writers; see SQL constraints. Our Python JSON guide shows custom encoders if you prefer to handle enums globally.
Enums with match statements
def ship(s: Status):
match s:
case Status.PAID:
return "ship it"
case Status.PENDING:
return "wait"
case _:
return "no action"
ship(Status.PAID), ship(Status.REFUNDED) # ('ship it', 'no action')
Dotted names like Status.PAID in a case are value patterns, compared by equality, so enums read naturally in pattern matching. Type checkers such as mypy can even warn when a match over an enum misses a member, if you replace the catch-all with explicit cases.
Which enum type should you use?
| Need | Use |
|---|---|
| Strict, type-safe constants | Enum |
| Values travel as text (JSON, APIs, DB) | StrEnum |
| Ordered levels or numeric codes | IntEnum |
| Combinable options | Flag |
| Values do not matter | Enum with auto() |
Common enum mistakes
- Comparing a plain
Enummember with a string and getting False. - Using
auto()for values that are persisted, then inserting a member in the middle. - Calling
json.dumpson members without converting them. - Accidental duplicate values creating aliases; use
@unique. - Using enums for data that changes at runtime, such as a product catalogue.
- Mixing
Status.PAID.nameand.value: store values, display names or labels.
Final thoughts
A Python enum is a small investment that removes a whole class of bugs. Define allowed values once, convert raw input with Status(value), compare members by identity, and pick StrEnum, IntEnum or Flag when you need text, ordering or combinations. Store values, not names, and keep enums for genuinely fixed sets. For lookups keyed by enum members, our Python dictionary guide is a good companion.
Frequently asked questions
What is an enum in Python?
An enum is a class whose members are a fixed set of named constants, created with the enum module. Each member has a name and a value and is a singleton.
How do I get an enum member from its value?
Call the enum class with the value, for example Status with the string paid. It returns the matching member or raises ValueError if no member has that value.
Why is my enum member not equal to its value?
Plain Enum members are deliberately not equal to their raw values. Compare with the member itself, use .value, or switch to IntEnum or StrEnum, whose members equal their values.
What does auto do in a Python enum?
auto assigns values automatically. In a normal Enum it counts from 1, and in a StrEnum it uses the lowercase member name. Avoid it for values you store or send over an API.
How do I convert an enum to JSON?
Serialise the member value, such as Status.PAID.value, and rebuild the member with Status(value) when reading. StrEnum and IntEnum members serialise directly as strings and numbers.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.