Sub topic 9
Comparing against constants and enum members
This chapter assumes you know the literal and capture patterns from earlier chapters, and that you have used enum.Enum in Python 3.10 or later. It covers how to compare a subject against a named constant inside a case.
Why a bare name does not work
A literal pattern such as case 404: compares the subject with a fixed value. Hard-coded numbers are hard to read, so you may want a named constant instead. A bare name in a pattern does not read a variable. It is a capture pattern, so it binds the subject to that name.
RED = 1
def describe(c):
match c:
case RED:
return f"captured {RED}"
print(describe(99)) # captured 99Here RED matched 99 and was overwritten with it. This case always succeeds. If you add another case after it, Python raises a SyntaxError, because the capture makes the later cases unreachable.
Value patterns use dotted names
A name containing a dot is a value pattern. Python looks the name up and compares it with the subject using ==. It does not bind anything. The dot is what tells the compiler to compare instead of capture.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
def warmth(c):
match c:
case Color.RED:
return "warm"
case Color.GREEN | Color.BLUE:
return "cool"
case _:
return "not a color"
print(warmth(Color.BLUE)) # cool
print(warmth(1)) # not a colorThe last call prints not a color because a plain Enum member does not equal the integer 1. With enum.IntEnum, members are integers, so 1 would match Color.RED.
The diagram shows how Python reads a name in a pattern.
Constants that are not enums
Module-level constants have no dot, so they cannot be used directly. You have two common options. Put them in a class as a namespace, or reference them through a module.
class Status:
OK = 200
NOT_FOUND = 404
def label(code):
match code:
case Status.OK:
return "fine"
case Status.NOT_FOUND:
return "missing"
case _:
return "other"
print(label(404)) # missingThe standard library follows the same idea. http.HTTPStatus is an IntEnum, so case HTTPStatus.OK: matches the integer 200.
Details to remember
- The comparison is
==, so any object with a suitable__eq__can match. - The value is looked up when the
caseis tried. It is not fixed when the function is defined. None,True, andFalseare matched withis, not==. Write them without a dot.- Dotted names can be nested, such as
case config.Mode.FAST:.
Exercise
What does this function return for check(5), and why?
LIMIT = 10
def check(n):
match n:
case LIMIT:
return "at limit"
case _:
return "other"
Show answer
It does not run at all. LIMIT has no dot, so it is a capture pattern that matches any value. Because it is followed by the _ case, Python raises a SyntaxError saying the name capture makes the remaining patterns unreachable. To compare with the constant, use a dotted name such as Limits.LIMIT or a literal 10.