Sub topic 2
Matching literal values
This chapter assumes Python 3.10 or later, and that you can write functions and if/elif chains. It also assumes you know the difference between == (equal value) and is (same object). You have already seen the shape of a match statement. Here you will learn exactly what a literal pattern is and how Python compares it with the subject.
What a literal pattern is
A literal pattern is a value written directly after case. The match line gives the subject, which is the value being tested. Each case line holds a pattern. When the subject fits the pattern, Python runs that case's block.
The literals you can use are:
- integers, including signed (
-1), hexadecimal (0x1F), and underscored (1_000) forms - floats such as
3.14 - complex numbers in the form
1+2j - strings and bytes, including raw strings and adjacent strings that Python joins together (
"a" "b") - the three singletons
None,True, andFalse
def describe(value):
match value:
case 0:
return "zero"
case -1:
return "minus one"
case 3.14:
return "pi-ish"
case "yes":
return "affirmative"
case b"\x00":
return "null byte"
case None:
return "nothing"
case True:
return "true"
case _:
return "other"
print(describe(-1)) # minus one
print(describe("yes")) # affirmative
print(describe(None)) # nothing
print(describe(42)) # otherThe last case, case _, is a wildcard that matches anything. It is the default branch. A later chapter covers it in detail. Here, read it as "everything else".
How the comparison works
Python does not use one rule for every literal. There are two.
None,True, andFalseare compared by identity, as if you wrotesubject is None.- Every other literal is compared by equality, as if you wrote
subject == literal.
Equality has consequences, because Python's == treats some different types as equal.
Gotcha: numbers that are equal across types
In Python, True == 1, False == 0, and 1.0 == 1. A literal number pattern therefore matches more than you might expect.
def check(value):
match value:
case 0:
return "zero"
case 1:
return "one"
case True:
return "true"
case _:
return "other"
print(check(0.0)) # zero
print(check(False)) # zero
print(check(True)) # onecheck(True) returns "one", not "true". The case 1 line comes first, and True == 1 is true, so it wins. The case True line is never reached for the subject True.
The reverse does not happen. The pattern True uses identity, and 1 is True is false, so case True never matches the integer 1.
When you mix booleans and numbers, put the True and False cases first:
def label(flag):
match flag:
case True:
return "bool true"
case False:
return "bool false"
case 1:
return "int one"
case 0:
return "int zero"
case _:
return "other"
print(label(True)) # bool true
print(label(1)) # int one
print(label(1.0)) # int one
print(label(0)) # int zeroFloats follow normal float rules. A literal pattern does not round or use a tolerance.
def check_float(x):
match x:
case 0.3:
return "matched"
case _:
return "no match"
print(check_float(0.3)) # matched
print(check_float(0.1 + 0.2)) # no match0.1 + 0.2 is 0.30000000000000004, which is not equal to 0.3. If you need approximate comparison, use math.isclose in an if, or in a guard (covered in a later chapter).
Strings are exact
String patterns compare with ==, so they are case-sensitive and whitespace-sensitive. "quit" does not match "Quit" or "quit ". Normalize the subject before the match instead of writing a case for every spelling.
def command(text):
match text.strip().lower():
case "start":
return "starting"
case "stop":
return "stopping"
case _:
return "unknown"
print(command(" START ")) # starting
print(command("Stop")) # stopping
print(command("pause")) # unknownThe subject expression runs once, before any case is tried. A function call there does not repeat for each case.
def next_value():
print("evaluated")
return 2
match next_value():
case 1:
print("one")
case 2:
print("two")This prints evaluated once, then two.
A str pattern never matches a bytes subject, because "a" == b"a" is false. Python 3 does not compare the two types as equal. (Running Python with the -b flag can warn about that comparison.)
What you cannot write
A literal pattern must be a plain literal, not an expression. Python rejects anything else when it compiles the code.
| Written after `case` | Allowed | Reason |
|---|---|---|
| `-5` | Yes | A signed number is a literal pattern |
| `1+2j` | Yes | The complex form is a literal |
| `0x1F` | Yes | A hexadecimal integer |
| `"a" "b"` | Yes | Adjacent strings join into one literal |
| `2 + 3` | No | Arithmetic is an expression, so this is a syntax error |
| `-x` | No | A negated name is not a literal |
| `f"v{n}"` | No | An f-string is computed at run time |
| `limit` | Not as a comparison | A bare name captures the subject instead of comparing it |
The last row is the most important one. A bare name such as limit is a capture pattern. It matches anything and binds the subject to that name. To compare against a named constant, use a dotted name such as Color.RED. A later chapter covers this and the pitfall it causes.
No match, no fall-through
Three rules follow from how match works.
- Python tries cases from top to bottom and runs only the first one that matches. There is no
break, and no fall-through to the next case. - If no case matches and there is no wildcard, nothing happens. Python raises no error. A function that returns from inside the cases returns
None. - Literal patterns of different types can sit in the same
match. The subject only has to equal one of them.
def http_status(code):
match code:
case 200:
return "OK"
case 301 | 302:
return "Redirect"
case 404:
return "Not Found"
case _:
return "Unknown"
print(http_status(302)) # Redirect
print(http_status(500)) # Unknowncase 301 | 302 is an or-pattern. It means "301 or 302". The next chapters cover it fully. Here it only shows that several literals can share one block.
Because a missing wildcard fails silently, add a case _ that handles or reports unexpected input whenever the subject comes from outside your program. Raising an error there turns a silent bug into a visible one:
def level(name):
match name:
case "debug":
return 10
case "info":
return 20
case _:
raise ValueError(f"unknown level: {name!r}")
print(level("info")) # 20When literals are enough
Literal patterns on their own behave like a switch statement. They are a good fit when you are choosing among a small set of fixed values, such as status codes, command names, or mode flags. If you only ever write literal cases on a single value, a dictionary lookup or an if/elif chain is also fine. The value of match grows once you destructure sequences, mappings, and objects, which later chapters cover.
Exercise
What does this code print? match True: with case 1: print("one") first and case True: print("true") second.
Show answer
It prints "one". The pattern 1 is compared with ==, and True == 1 is true, so the first case wins. The pattern True is never reached. Putting case True first would print "true".
Exercise
A function runs match 0.1 + 0.2: with case 0.3: return "matched" and no wildcard. What does it return, and why?
Show answer
It returns None. The sum is 0.30000000000000004, which is not equal to 0.3. No case matches, and a match with no wildcard does nothing and raises no error, so the function ends without a return value.
Exercise
Why does case 2 + 3: fail, and what is the one allowed form of addition in a literal pattern?
Show answer
A literal pattern must be a plain literal, not an expression, so Python reports a syntax error. The only allowed sum is the complex-number form, such as case 1+2j.