Lesson 20 of 52Objects
Enums
Replace magic strings with Enum, StrEnum, IntEnum and Flag, add behaviour to members, and handle every case safely from JSON to the database.
Somewhere in every codebase there is a line like if order.status == "shiped":. It has a typo, it never matches, and nothing complains. The status values live as bare strings in twenty files, nobody knows the full list, and adding a new one means a grep and a prayer. An enum fixes this: one class that is the single source of truth for a fixed set of values, where a typo is an AttributeError the moment the line runs and a type checker can tell you when you forgot a case. You met Enum briefly in the Standard Library Tour. This lesson goes deep enough to use enums well in production code.
The bug enums prevent
Here is the magic-string version of an order workflow, next to the enum version.
Press Run (⌘ Enter) to see what happens.Three things just happened. The set of legal values is written down once. A misspelt member is an error, not a silent False. And your editor can autocomplete Status. and show you every option. Those three properties are the whole case for enums.
Members, names and values
An enum class is not a normal class. When Python creates Status, a metaclass called EnumType turns each class attribute into a member: a single instance of Status that carries a .name (the attribute name, always a string) and a .value (whatever you assigned). You never construct members yourself. Calling the class looks up an existing member instead.
Press Run (⌘ Enter) to see what happens.The two lookups are worth separating clearly in your head. Color["RED"] uses the name and raises KeyError if it is missing. Color("red") uses the value and raises ValueError. When you parse input from a form or an API, you almost always want the value lookup, because the value is what you store and send.
Members are singletons. There is exactly one Color.RED object in the process, and copying or pickling a member gives you the same object back. That is why is is safe for comparing members, and why members are hashable and work as dict keys and set members. == works too; prefer is in hot code and pick one style per codebase.
Since Python 3.12, "red" in Color checks values and returns True. On older versions a non-member raised TypeError, so you may see value in Color._value2member_map_ or a try around Color(value) in older code.
class Size(Enum): SMALL = 's'; LARGE = 'l', which expression raises a KeyError?Aliases, auto() and @unique
Two members with the same value make the second one an alias. That can be useful (CRIMSON as a legacy spelling of RED), but usually it is a copy-paste mistake. Decorate the class with @unique and Python raises ValueError at class creation if any value repeats.
When the values themselves do not matter, use auto(). In a plain Enum it counts up from 1. In a StrEnum it produces the lowercased member name, which is usually exactly what you want for JSON and databases.
Press Run (⌘ Enter) to see what happens.A warning about auto() with plain Enum: the numbers depend on the order of the members. Insert a new member in the middle and every member after it changes value. If those integers were ever written to a database or a file, you just corrupted the meaning of old rows. Use auto() with integers only for values that never leave the process, or use StrEnum, where auto() follows the name instead of the position.
StrEnum and IntEnum: members that are also plain values
A plain Enum member is not equal to its value. Color.RED == "red" is False, and json.dumps(Color.RED) raises TypeError. That strictness is a feature inside your code, but it is friction at the edges, where data becomes JSON, SQL parameters or log lines.
StrEnum (Python 3.11) and IntEnum fix that by making each member a real str or int as well. They compare equal to plain values, serialise without help and pass isinstance(x, str).
Press Run (⌘ Enter) to see what happens.The last line is the danger of IntEnum. Because members are integers, they compare equal to any integer with the same value, including a member of a completely unrelated enum. A refactor that passes HttpRetries.MAX where a Priority was expected will not fail at runtime. You gave up the type safety that made the enum worth having.
The practical rule most teams settle on:
StrEnumfor values that cross a boundary: API fields, database columns, config keys, event names. Readable in logs and JSON, safe to compare with incoming strings.IntEnumonly when you need integer behaviour, such as interop with a C library or an existing protocol that uses numeric codes, or sorting by numeric rank.- Plain
Enumfor internal states where you want strictness and nothing outside sees the value.
Note that since Python 3.11, str() and format() of a StrEnum or IntEnum member give the plain value ("paid", "3"), while repr() still shows <Status.PAID: 'paid'>. If an old log format suddenly changed after an upgrade, this is a likely reason.
What does this print?
from enum import Enum, StrEnum
class A(Enum):
X = "x"
class B(StrEnum):
X = "x"
print(A.X == "x", B.X == "x", A("x") is A.X)Flag and IntFlag: sets of options in one value
Some values are not one choice but a combination: file permissions, feature toggles, notification channels. Flag members are powers of two, and you combine them with |, test membership with in, and remove with & ~. Under the hood each member is one bit, and a combination is just those bits OR-ed together into one integer.
auto() in a Flag gives powers of two: READ = 1, WRITE = 2, EXECUTE = 4. Each member owns exactly one bit.
Press Run (⌘ Enter) to see what happens.IntFlag is the integer-mixin version, used where the numbers must interoperate with the OS or a wire protocol (Python's own re.IGNORECASE and friends are an IntFlag). The same equality leak as IntEnum applies. For flags you store in your own database, a plain Flag serialised as its .value integer is compact, but a list of names is far easier to read and migrate. Choose deliberately.
Behaviour on members
Enums are classes, so they can have methods and properties. This is how you stop logic about a status from leaking into every caller. Instead of if s in ("shipped", "cancelled") copied around the codebase, the enum answers the question itself.
_missing_ is a classmethod hook that Python calls when a value lookup fails. Return a member to accept the input, or return None to let the normal ValueError happen. It is the clean place for lenient parsing: trimming whitespace, ignoring case, or mapping unknown values to a safe fallback.
Press Run (⌘ Enter) to see what happens.Be careful with an UNKNOWN fallback. It keeps a consumer alive when a newer producer sends a status it does not know yet, which is exactly what you want when reading events from another team's service. But it can also hide real bugs. Log every fallback, and do not use one for values your own code writes.
You also cannot subclass an enum that already has members: class More(Status): ... raises TypeError. Enums are closed sets on purpose. Share behaviour through a base enum without members, or through plain functions.
How Python builds an enum class
Enum uses a metaclass, EnumType (still also available under its old name EnumMeta). When the class body finishes running, the metaclass walks the namespace. Anything that is a function, a descriptor such as property, or a name starting and ending in underscores is left alone. Every other attribute becomes a member: Python creates one instance, stores the name and value on it, and records it in two dicts. _member_map_ maps names to members (that is what Color["RED"] and __members__ read), and _value2member_map_ maps values to members, which is why Color("red") is a fast dictionary lookup rather than a loop.
Color("red") looks like a constructor call, but EnumType.__call__ intercepts it and does the lookup. If the value is not in the map, it calls _missing_. Because the metaclass also blocks reassigning members (Color.RED = 5 raises AttributeError), the set of members is fixed for the life of the process.
If you want a class attribute that is not a member, wrap it in enum.nonmember(...) (3.11), and if you want a nested function to become a member, wrap it in enum.member(...).
Exhaustive handling with match and assert_never
The biggest payoff of an enum is that a type checker knows the complete list of members. Combine it with match and typing.assert_never (3.11) and you get a compile-time reminder whenever someone adds a member and forgets to handle it.
Press Run (⌘ Enter) to see what happens.At runtime, assert_never raises AssertionError with the unexpected value. The real win happens before runtime: mypy or pyright narrows channel after each case, sees that Channel.PUSH is still possible when it reaches assert_never, and reports an error on that line. Run the checker in CI and adding a member becomes a guided task: the checker lists every function you still need to update.
Note the dotted name Channel.EMAIL in each case. A bare name such as case EMAIL: would not compare against anything; it would capture any value into a new variable called EMAIL. The Structural Pattern Matching lesson covers that trap in detail.
You add Channel.WHATSAPP to a codebase that uses the match plus assert_never pattern. Put the steps in the order they happen.
- Tap the steps below in the right order.
Enums at the boundaries: JSON, Pydantic and databases
Inside your code, members are objects. At the edges they become strings or numbers, and that conversion is where enum bugs actually happen at work.
JSON. StrEnum members serialise as their value with no extra code. To read them back, call Status(raw). For a plain Enum, you need default=lambda o: o.value in json.dumps or an explicit .value.
Pydantic. A model field typed as Status validates incoming strings against the enum values and gives you the member. Invalid input becomes a clear validation error listing the allowed values, and the generated OpenAPI schema shows the options. FastAPI relies on this.
SQLAlchemy. An Enum column type maps members to the database. By default it stores the member names, not the values; there is an option (values_callable) to store values instead. Check which one your project uses before writing a raw SQL query against that column. Check the current SQLAlchemy docs for the exact options.
Migrations. This is the part seniors worry about. Renaming a member, or changing a value, breaks every row already stored under the old one. Removing a member breaks old rows and any older service still sending it. With a PostgreSQL native ENUM type, adding a value is a simple ALTER TYPE ... ADD VALUE, but there is no command to remove one, so cleaning up means recreating the type. That is why many teams store enums as plain text columns with a CHECK constraint or no constraint at all, and keep the enum in application code. The rules that save you:
- Treat a stored value like a public API. Never rename it; add a new member and migrate rows.
- Deploy readers before writers. Ship the code that understands a new value before any code that writes it.
- Decide what old code does with a value it does not know: fail, or fall back through
_missing_.
Pick the best tool for each job.
- member
- One of the fixed, singleton instances of an enum class, with a
.nameand a.value. - alias
- A second name for an existing member, created when two attributes share a value.
@uniqueforbids them. - auto()
- Picks a value for you: counting integers in
Enum, powers of two inFlag, the lowercased name inStrEnum. - StrEnum
- An enum whose members are also real strings, so they compare equal to and serialise as their values (3.11+).
- Flag
- An enum whose members are bits that combine with
|and are tested within. - _missing_
- A classmethod hook called when a value lookup fails, used for lenient parsing or a fallback member.
- assert_never
- Marks code as unreachable, so a type checker reports any enum member a
matchforgot to handle.