Sub topic 8
Using Enums in Type Hints, Dictionaries and match
This chapter assumes you can define an Enum, read .name and .value, and look members up with Color(2) or Color["BLUE"]. It also assumes you know the difference between == and is, and that you have written a basic match statement. The chapter covers three places where enums do the most work in real code: type annotations, dictionary keys, and match statements. It also covers how data from outside your program becomes an enum member, because that is where most bugs appear.
Enums as type hints
An enum class is also a type. Annotating a parameter with the class says "this function takes a member of this enum, not a raw string or integer."
from enum import Enum
class Command(Enum):
START = "start"
STOP = "stop"
RESTART = "restart"
def describe(cmd: Command) -> str:
return f"{cmd.name} ({cmd.value})"
print(describe(Command.START)) # START (start)Python does not check annotations at run time. describe("start") fails only when the function body touches .name, and a function that never touches it would accept the string silently. The benefit comes from a static type checker such as mypy or pyright. It rejects describe("start") and also flags a misspelled member such as Command.STOPP.
Two annotation forms come up often:
Command | None(Python 3.10+) for a value that may be absent, such as the result of a failed parse.Literal[Command.START](fromtyping) when a function accepts only one member or a subset of members. Type checkers treat each enum member as a literal type.
from typing import Literal
def run_startup(cmd: Literal[Command.START, Command.RESTART]) -> str:
return f"running {cmd.value}"
print(run_startup(Command.RESTART)) # running restartPassing Command.STOP here is a type-checker error, but it still runs at run time. The hint is documentation that tools can verify, not a guard.
Converting outside data into members
Data from files, HTTP requests and command lines arrives as plain strings or integers. Convert it once, at the edge of your program, and pass members everywhere else. Calling the class does the conversion, and a failed lookup raises ValueError.
def parse(text: str) -> Command | None:
try:
return Command(text)
except ValueError:
return None
print(parse("stop")) # Command.STOP
print(parse("explode")) # NoneWhether to return None, re-raise with a better message, or fall back to a default depends on the caller. For user input, a clear error message listing the valid values is usually the most helpful:
def parse_strict(text: str) -> Command:
try:
return Command(text)
except ValueError:
valid = ", ".join(c.value for c in Command)
raise ValueError(f"unknown command {text!r}; expected one of: {valid}") from None
print(parse_strict("start")) # Command.STARTEnums as dictionary keys
Enum members are hashable, so they work as dictionary keys and set elements. A plain Enum hashes by member name, and two different members never compare equal, so lookups behave like lookups on unique constants.
from collections.abc import Callable
HANDLERS: dict[Command, Callable[[], str]] = {
Command.START: lambda: "starting",
Command.STOP: lambda: "stopping",
Command.RESTART: lambda: "restarting",
}
def dispatch(cmd: Command) -> str:
return HANDLERS[cmd]()
print(dispatch(Command.STOP)) # stoppingA dispatch table like this has two advantages over a chain of if statements. The table is data, so you can build it, extend it or test it separately. It also lets you check completeness once, at import time, instead of discovering a missing case in production:
missing = set(Command) - set(HANDLERS)
if missing:
raise RuntimeError(f"no handler for: {sorted(m.name for m in missing)}")Keys must be members, not their values. With a plain Enum, HANDLERS["start"] raises KeyError, because Command.START == "start" is False and their hashes differ. That is usually what you want, since it stops raw strings from slipping past your conversion step. It is also why the dictionary type hint matters: dict[Command, ...] tells readers and checkers that the keys are members.
The mixin enums from the later IntEnum and StrEnum chapter behave differently. An IntEnum member hashes and compares like its integer, so it matches an int key:
from enum import IntEnum
class Priority(IntEnum):
LOW = 1
HIGH = 3
labels = {Priority.LOW: "low", Priority.HIGH: "high"}
print(labels[1]) # lowThat convenience is also a way for unchecked integers to reach your code, so use it deliberately.
Dictionaries for per-member data
Another common use is a dictionary that holds data for each member without cluttering the enum class. Using Command as the key type keeps the mapping closed, since you can build it from Command itself:
counts: dict[Command, int] = {cmd: 0 for cmd in Command}
counts[Command.START] += 1
print(counts)
# {<Command.START: 'start'>: 1, <Command.STOP: 'stop'>: 0, <Command.RESTART: 'restart'>: 0}Iterating over Command skips aliases, so each canonical member gets exactly one entry. If the data belongs to the member permanently, consider a field or property on the enum instead, as in the earlier chapter on methods and fields. Use an external dictionary when the data belongs to one subsystem and the enum is shared by many.
Enums in match statements
The match statement (Python 3.10+) reads naturally with enums. A dotted name such as Command.START in a case is a value pattern. Python evaluates it and compares the subject to the result with ==.
def run(cmd: Command) -> str:
match cmd:
case Command.START:
return "starting"
case Command.STOP:
return "stopping"
case Command.RESTART:
return "restarting"
print(run(Command("restart"))) # restartingYou can group members with |, and add a guard with if:
def is_disruptive(cmd: Command, force: bool) -> bool:
match cmd:
case Command.STOP | Command.RESTART if force:
return True
case _:
return False
print(is_disruptive(Command.STOP, True)) # True
print(is_disruptive(Command.STOP, False)) # FalseChecking that every member is handled
If you add PAUSE to Command later, the run function above falls off the end of the match and returns None. You can make that mistake visible to a type checker with assert_never (in typing since Python 3.11):
from typing import assert_never
def run_checked(cmd: Command) -> str:
match cmd:
case Command.START:
return "starting"
case Command.STOP:
return "stopping"
case Command.RESTART:
return "restarting"
case _:
assert_never(cmd)After the three cases, the checker narrows cmd to "no members left", so assert_never(cmd) type-checks. Add a new member and cmd still has a possible type at that point, so the checker reports an error on that line. At run time, assert_never raises AssertionError if it is ever reached.
Bare names capture; dotted names compare
This is the most common mistake with match and enums. A bare name in a case is a capture pattern. It matches anything and binds the name.
| Pattern | Meaning |
|---|---|
| `case Command.START:` | Value pattern. Matches if `subject == Command.START`. |
| `case START:` | Capture pattern. Matches everything and assigns the subject to a new variable `START`. |
| `case Command():` | Class pattern. Matches any `Command` member (an `isinstance` check). |
| `case "start":` | Matches only a string equal to `"start"`. A plain `Enum` member never equals it. |
If you import members directly with from commands import START, you still need the dotted form or a value pattern workaround, because a bare START in a case will not be compared. Python helps in one situation: a capture pattern followed by more cases is a SyntaxError. As the last case it silently matches everything, so a typo can hide.
def broken(cmd: Command) -> str:
match cmd:
case START: # capture pattern: matches every subject
return "start"
print(broken(Command.STOP)) # startThe output is wrong for Command.STOP, and nothing raised an error. Always qualify enum members with the class name in patterns.
Matching on values instead of members
If the subject is a raw string, case Command.START will not match, because a plain Enum member does not equal its value. You have two clean options. Convert first, then match on members:
def run_text(text: str) -> str:
return run_checked(Command(text))
print(run_text("start")) # startingOr match on cmd.value with string literals. The first option is better, because Command(text) rejects invalid input before it reaches your logic, and the match then works with a closed set of members.
Choosing between dictionaries and match
Both dispatch on a member. They suit different jobs.
| Situation | Better fit |
|---|---|
| Each member maps to a callable or constant, and the mapping may be extended or tested | Dictionary |
| You need a startup check that no member is missing | Dictionary (set difference) |
| Cases need guards, grouped members, or unpacking of other data | `match` |
| You want the type checker to report unhandled members | `match` with `assert_never` |
| Python version is older than 3.10 | Dictionary |
Common errors
- Passing the value where a member is expected.
describe("start")runs until it touches an enum attribute. Convert withCommand(text)at the boundary and let the type checker enforce the rest. - Using a raw value as a dictionary key.
HANDLERS["start"]raisesKeyErrorfor a plainEnum. Convert first. - Writing a bare name in a
case. It captures instead of comparing. UseCommand.START. - Assuming a
matchis exhaustive. Without acase _that callsassert_never, an unhandled member quietly returnsNonefrom a function. - Catching
ValueErrortoo broadly. Wrap only theCommand(text)call intry, so aValueErrorfrom your own logic is not mistaken for a bad lookup.
Exercise
Given class Mode(Enum): READ = "r"; WRITE = "w", what does {Mode.READ: 1}["r"] do, and what does match Mode.READ with case "r": do? How would you fix the code so a string "r" selects the read behavior?
Show answer
Both fail to match. The dictionary lookup raises KeyError, because a plain Enum member hashes and compares differently from its value "r". The case "r": never matches, because Mode.READ == "r" is False. Fix it by converting at the boundary with Mode("r"), which returns Mode.READ, and then using the member for the dictionary lookup and for case Mode.READ:.
Exercise
Write a describe(cmd: Command) -> str function that uses match with Command.START | Command.RESTART in one case and Command.STOP in another, and ends with case _: assert_never(cmd). What happens, for a static checker and at run time, if you later add PAUSE = "pause" to Command?
Show answer
The function is match cmd: with case Command.START | Command.RESTART: return "running", case Command.STOP: return "stopped", and case _: assert_never(cmd). After adding PAUSE, a static checker reports an error on the assert_never(cmd) line, because cmd can still be Command.PAUSE there. At run time, calling describe(Command.PAUSE) reaches assert_never and raises AssertionError.