Sub topic 9
Comparing against constants and enum members
This chapter assumes you know how match and case blocks work, what a capture pattern is, and how to define an Enum. It covers how to compare a subject against a named constant, which is where many first-time users of match get surprised.
The problem: a bare name captures
In a case pattern, a plain name such as RED is never a lookup. It is a capture pattern, which binds the subject to that name and always succeeds. Take this code:
RED = "red"
def probe(subject):
match subject:
case RED:
return f"captured {RED!r}"
print(probe("blue")) # captured 'blue'The program never compares "blue" with the module-level RED. The case RED line creates a local variable named RED inside probe and assigns the subject to it. Any value, including "blue", matches.
Python catches the most obvious form of this mistake. If you put another case after a bare-name case, the compiler refuses the code:
RED = "red"
def describe(color):
match color:
case RED:
return "red"
case _:
return "other"This fails with SyntaxError: name capture 'RED' makes remaining patterns unreachable. The error appears only when something follows the bare name. If the bare name is the last case, nothing warns you, as the first example shows.
Value patterns: dotted names are compared
A dotted name is the fix. A name containing at least one dot, such as Color.RED or settings.MODE, is a value pattern. Python looks the name up and compares it with the subject using ==. It never binds anything.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
def name(c):
match c:
case Color.RED:
return "red"
case Color.GREEN:
return "green"
case _:
return "other"
print(name(Color.GREEN)) # green
print(name(1)) # otherThe last line shows a point that matters in practice. Color.RED == 1 is False for a plain Enum, so the integer 1 does not match case Color.RED.
The rule is purely syntactic. The dot is what tells Python to look the name up. No other property of the name, such as ALL_CAPS style or being defined at module level, changes the behavior.
| Pattern written | Kind | What happens |
|---|---|---|
| `case RED:` | Capture | Binds the subject to `RED`. Always matches. |
| `case _:` | Wildcard | Matches anything. Binds nothing. |
| `case Color.RED:` | Value | Matches if `subject == Color.RED`. |
| `case 404:` | Literal | Matches if `subject == 404`. |
| `case None:` | Literal | Matches if `subject is None`. |
Using enums as the standard case
Enums are the natural fit for value patterns, because their members are already reached through a dotted name. A typical use is a function that branches on a state:
from enum import Enum
class State(Enum):
IDLE = "idle"
RUNNING = "running"
FAILED = "failed"
def next_action(state):
match state:
case State.IDLE:
return "start"
case State.RUNNING:
return "wait"
case State.FAILED:
return "retry"
case _:
raise ValueError(f"unexpected state: {state!r}")
print(next_action(State.RUNNING)) # waitThe final case _ is deliberate. If someone adds a member to State later and forgets to update this function, the error shows up immediately instead of the function silently returning None.
Value patterns also work inside larger patterns, and you can combine them with |:
from enum import Enum
class Direction(Enum):
NORTH = "n"
SOUTH = "s"
EAST = "e"
WEST = "w"
def describe(command):
match command:
case ("move", Direction.NORTH | Direction.SOUTH):
return "vertical move"
case ("move", Direction.EAST | Direction.WEST):
return "horizontal move"
case ("move", other):
return f"unknown direction {other!r}"
case _:
return "not a move"
print(describe(("move", Direction.SOUTH))) # vertical move
print(describe(("move", "up"))) # unknown direction 'up'Here Direction.NORTH is compared, while other in the third case is a capture. Both appear in the same pattern language, and the dot is the only difference between them.
Equality is `==`, so mixins matter
Because value patterns use ==, the result depends on how the enum defines equality. Three cases come up often:
- A plain
Enummember equals only itself. Raw values such as1or"red"do not match. - An
IntEnummember equals its integer value, so integers match. - An enum that also inherits from
strequals its string value.
from enum import Enum, IntEnum
from http import HTTPStatus
class Mode(str, Enum):
READ = "r"
WRITE = "w"
def mode_label(m):
match m:
case Mode.READ:
return "read-only"
case Mode.WRITE:
return "writable"
case _:
return "unknown"
def status_label(code):
match code:
case HTTPStatus.OK:
return "fine"
case HTTPStatus.NOT_FOUND:
return "missing"
case _:
return "other"
print(mode_label("r")) # read-only
print(status_label(404)) # missing
print(isinstance(HTTPStatus.OK, IntEnum)) # TrueHTTPStatus is an IntEnum, so the plain integer 404 matches HTTPStatus.NOT_FOUND. That convenience is useful when data arrives from outside your program, such as JSON or a network response. The same convenience can hide bugs, though. If you want only real enum members to match, use a plain Enum and convert incoming data explicitly, for example Mode("r").
Constants that are not enum members
Module-level constants cannot be used directly, because they have no dot. You have three options:
- Reach the constant through its module, as in
case config.MAX_RETRIES. This is the usual choice when the constant lives in another module. - Group constants in a class or enum, as in
case Limits.MAX. - Use a literal and put the name in a comment, which is simple but duplicates the value.
class Limits:
MIN = 0
MAX = 100
def clamp_label(n):
match n:
case Limits.MIN:
return "at minimum"
case Limits.MAX:
return "at maximum"
case _:
return "in between"
print(clamp_label(100)) # at maximum
print(clamp_label(7)) # in betweenA value pattern can also appear as a field of a class pattern. This lets you test a single attribute against a constant:
from dataclasses import dataclass
class Role:
ADMIN = "admin"
@dataclass
class User:
name: str
role: str
def greet(user):
match user:
case User(role=Role.ADMIN, name=name):
return f"welcome back, {name} (admin)"
case User(name=name):
return f"hello, {name}"
case _:
return "who are you?"
print(greet(User("Ada", "admin"))) # welcome back, Ada (admin)
print(greet(User("Bo", "guest"))) # hello, BoLiterals `None`, `True`, and `False`
Three literals are compared with is instead of ==: None, True, and False. This avoids a confusing result. In Python, True == 1 and False == 0, so a number could otherwise match a Boolean pattern.
def kind(x):
match x:
case True:
return "the Boolean True"
case 1:
return "the number one"
case None:
return "nothing"
case _:
return "something else"
print(kind(True)) # the Boolean True
print(kind(1)) # the number one
print(kind(1.0)) # the number oneThe reverse is not safe. If you swapped the order and wrote case 1 first, True would match it, because True == 1. Put Boolean cases before numeric ones whenever both can occur.
Practical checklist
- Use a dotted name whenever you want to compare against a constant.
- Prefer enums for related constants, and end with
case _that raises an error. - Remember that matching uses
==, soIntEnumandstr-mixin enums match raw values and plainEnumdoes not. - Place
TrueandFalsecases before numeric cases. - Do not try to write a computed expression such as
case Limits.MAX - 1. Patterns allow only names, literals, and the pattern syntax. Use a guard instead.
Exercise
This function is meant to return "stop" when the subject equals the constant STOP, but it returns "stop" for every value. Explain why and show the fix. STOP = "halt" def signal(msg): match msg: case STOP: return "stop"
Show answer
The bare name STOP is a capture pattern, so it binds msg to a new local name STOP and always matches. It does not compare against the module constant. Make the name dotted so it becomes a value pattern, for example by putting it in a class (class Signals: STOP = "halt") and writing case Signals.STOP:. Adding a final case _: is also a good idea so unmatched values are handled explicitly.
Exercise
Given class Level(IntEnum) with WARN = 30, and a plain class Kind(Enum) with WARN = 30, what do match 30: case Level.WARN: and match 30: case Kind.WARN: each do?
Show answer
The first matches, because an IntEnum member equals its integer value (Level.WARN == 30 is True). The second does not match, because a plain Enum member equals only itself (Kind.WARN == 30 is False), so the case is skipped and control moves to later cases.