Sub topic 8
Using enums in type hints, dictionaries and match
This chapter assumes you can define an Enum, read .name and .value, and know that members are singletons compared with is or ==. Here you will use enums as types, as dictionary keys, and as match patterns.
Enums as type hints
An enum class is a type. Annotate a parameter with it to say that only members are accepted:
from enum import Enum
class Command(Enum):
START = "start"
STOP = "stop"
def run(cmd: Command) -> None:
print(f"running {cmd.name}")
run(Command.START)
run(Command("stop"))Python does not check annotations at run time. run("start") still executes, and a type checker such as mypy or pyright is what rejects it. Convert raw input at the boundary of your program with Command(value), which raises ValueError for unknown values. Inside the program, pass only members.
Enums as dictionary keys
Members are hashable, so they work as dictionary keys. Their hash depends on the member's name, and each member is a single object. This makes a dictionary a simple dispatch table:
import math
from enum import Enum, auto
class Shape(Enum):
SQUARE = auto()
CIRCLE = auto()
AREA = {
Shape.SQUARE: lambda size: size * size,
Shape.CIRCLE: lambda size: math.pi * size * size,
}
print(AREA[Shape.SQUARE](3)) # 9
print(round(AREA[Shape.CIRCLE](1), 2)) # 3.14Keying by member rather than by string means a misspelled key raises AttributeError at the point where you write Shape.SQURE. A misspelled string key would only fail later, as a KeyError.
You can check that the table covers every member:
missing = set(Shape) - set(AREA)
assert not missing, f"no handler for {missing}"Iterating Shape skips aliases, so this check lists each real member once.
Branching with match
Structural pattern matching (Python 3.10+) treats a dotted name such as Command.START as a value pattern. It compares the subject to that member with ==.
from enum import Enum
class Command(Enum):
START = "start"
STOP = "stop"
def handle(cmd: Command) -> str:
match cmd:
case Command.START:
return "starting"
case Command.STOP:
return "stopping"
print(handle(Command("stop"))) # stoppingYou can combine members with | in one case:
def is_active(cmd: Command) -> bool:
match cmd:
case Command.START | Command.STOP:
return True
case _:
return FalseThe following diagram shows the path from raw input to a handler.
Missing cases
A match with no matching case does nothing. In handle above, a newly added Command.PAUSE would make the function return None. Add a final case that fails loudly:
def handle(cmd: Command) -> str:
match cmd:
case Command.START:
return "starting"
case Command.STOP:
return "stopping"
case _:
raise ValueError(f"unhandled command: {cmd!r}")Type checkers can also report non-exhaustive matches over an enum. Pyright does this when you enable its reportMatchNotExhaustive rule, and mypy has a similar check.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `case START:` instead of `case Command.START:` | Captures any value | Use the dotted name |
| `Command("START")` when the value is `"start"` | `ValueError`, because lookup is by value | Use `Command["START"]` for names |
| Matching a raw string against a plain `Enum` | No case matches, because `Command.START == "start"` is `False` | Convert first with `Command(raw)` |
| Handler table missing a member | `KeyError` at call time | Check `set(Shape) - set(AREA)` |
Exercise
Given class Level(Enum): LOW = 1; HIGH = 2, what does this function return for describe(Level.HIGH), and why does describe(2) return "other"?
def describe(x):
match x:
case Level.LOW:
return "low"
case Level.HIGH:
return "high"
case _:
return "other"
Show answer
describe(Level.HIGH) returns "high", because the value pattern Level.HIGH compares equal to the member. describe(2) returns "other", because a plain Enum member never equals its raw value, so neither dotted pattern matches and the wildcard case runs. With IntEnum, 2 == Level.HIGH would be True and the result would be "high".