Sub topic 13
Pitfalls: Bare Names, Unreachable Cases, and Mutable State
Most match bugs come from three sources. A bare name in a pattern captures instead of comparing. An earlier case hides a later one. Captured values and guards touch state you did not expect. This chapter shows each failure and how to avoid it.
This chapter assumes you know the pattern types from earlier chapters: literal, capture, wildcard, or, sequence, mapping, class, and value patterns. It also assumes you have used guards. You need Python 3.10 or later. The examples run as written.
Pitfall 1: A bare name captures, it does not compare
In a case pattern, a plain name such as RED is a capture pattern. It matches anything and binds the subject to that name. It does not look up the existing value of RED.
RED = "red"
match "blue":
case RED:
print("RED is now", RED)
print(RED)This prints RED is now blue and then blue. The case matched, and it overwrote your constant.
Python catches some of these mistakes at compile time. A capture pattern or _ always matches. If it appears in a case that is not the last one, the compiler raises a SyntaxError such as name capture 'RED' makes remaining patterns unreachable. So a misused constant followed by case _: fails loudly. The silent version is the one above, where the capture is the last or only case.
There are three ways to fix it:
- Use a dotted name such as
Color.REDorconfig.LIMIT. A dotted name is a value pattern and is compared with==. - Use a literal such as
"red"directly. - Keep the bare name as a capture and add a guard:
case c if c == RED:.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
def describe(color):
match color:
case Color.RED:
return "warm"
case Color.GREEN:
return "cool"
case _:
return "unknown"
print(describe(Color.RED)) # warmOther bare-name traps
case Point:(no parentheses) captures the subject under the namePoint. It does not check the type. Writecase Point():to test the class.case [x, y]:bindsxandy. It does not compare against existing variables of those names._is a wildcard and is never bound. Any other name is bound, including names you meant as throwaway values, such ascase [_, _]versuscase [a, a]. The second form is aSyntaxErrorbecause a name may be bound only once per pattern.
Pitfall 2: Unreachable and shadowed cases
Cases are tried from top to bottom, and the first match wins. The compiler only rejects the irrefutable case that is not last. It does not detect a specific case that a broader case above it makes dead.
def classify(value):
match value:
case int():
return "int"
case 0:
return "zero" # never reached for ints
case _:
return "other"
print(classify(0)) # int
print(classify("a")) # otherThe case 0: line cannot match anything that int() has not already matched. Python gives no warning. Put the narrow pattern first and the broad one after it.
The same shadowing happens with sequences. case [first, *rest]: matches every non-empty sequence, so a case [only]: below it never runs.
For the subject 0, the flow stops at the first decision. The case 0 branch exists in the code but is dead.
Literals are compared with `==`, with three exceptions
Literal patterns usually use ==. The singletons None, True, and False are compared with is. This produces surprising results because True == 1 and 1.0 == 1.
def kind(x):
match x:
case True:
return "true"
case 1:
return "one"
case _:
return "other"
print(kind(True)) # true
print(kind(1)) # one
print(kind(1.0)) # one
print(kind(2)) # otherIf you swapped the first two cases, kind(True) would return "one", because True == 1. When you need to tell booleans from integers, test bool first or use a class pattern such as case bool():.
Ordering with guards
A case with a guard can fail even when its pattern matches, and then matching continues downward. Order cases from most specific to most general. Put guarded cases before the unguarded case that would otherwise take their inputs.
Pitfall 3: Mutable state and side effects
Patterns look declarative, but they read and bind real objects. Three issues follow from that.
Captures are references, not copies
A capture pattern binds a name to the same object inside the subject. If that object is mutable, changing it changes the subject.
def mark_seen(event):
match event:
case {"queue": queue}:
queue.append("seen")
return event
data = {"queue": []}
mark_seen(data)
print(data) # {'queue': ['seen']}The function appears to only read the event, but it modifies the caller's data. The rules for the other captures are:
- A
*restcapture in a sequence pattern builds a new list. The elements inside it are still the original objects. - A
**restcapture in a mapping pattern builds a new dict. The values inside it are still the originals. - A direct capture such as
queueabove is the original object.
If you must modify what you captured, copy it first, for example list(queue).
Guards run code, possibly more than once
A guard is an arbitrary expression. It runs each time its case is reached and its pattern matches. If several cases call the same function, it runs once per case.
calls = 0
def is_big(n):
global calls
calls += 1
return n > 10
def label(n):
match n:
case int() if is_big(n):
return "big"
case int() if not is_big(n):
return "small"
print(label(3)) # small
print(calls) # 2The function was called twice for one subject. If is_big were a network call, a database query, or a counter, the result would be wrong or slow. Compute the value once before the match, or restructure so one guard decides.
The same applies to class patterns. case Point(x=0) reads the attribute x. If x is a property or the class defines __getattr__, that code runs during matching.
Bindings can outlive a failed match
Names bound by a successful match remain after the match statement ends. That is useful. The reverse is less obvious: a case can bind names and still fail, and the names may stay bound.
x = "original"
match 5:
case x if x > 10:
pass
print(x) # 5 in CPythonThe pattern x matched and bound x to 5. Then the guard failed, so the block did not run, but x was already overwritten. The language reference says not to rely on bindings from a failed match, and not to rely on variables staying unchanged either. Treat names as valid only inside the case body that matched.
Subjects that do not behave like sequences
Sequence patterns do not match str, bytes, or bytearray, even though they can be indexed. They also do not match iterators or generators, because those cannot be indexed or measured without consuming them. Convert first with list(...), and be aware that doing so consumes the iterator.
Summary of pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
| Bare constant name | Case always matches; constant overwritten | Dotted name, literal, or guard |
| `case Point:` without parentheses | Matches any value | Write `case Point():` |
| Broad case above narrow case | Narrow case never runs | Order from specific to general |
| `case 1` and booleans | `True` and `1.0` match `1` | Test `bool` first, or use a class pattern |
| Capturing a mutable value | Caller's data is changed | Copy before modifying |
| Side effects in guards | Function runs repeatedly | Compute once before `match` |
| Reading names after a failed case | Unexpected bound values | Use names only inside the matched body |
Checking your own code
A short review routine finds most of these bugs:
- Read each
caseand ask whether every bare name is meant to receive a value. If it is meant to be compared, make it dotted. - Read the cases top to bottom and ask whether any earlier case could match everything a later one matches.
- Look at each guard for function calls, and at each captured mutable value for later mutation.
- Add a test that sends a value into every case, including the default. A case that no test can reach is a sign of shadowing.
Exercise
This function should return "stop" when the light is the constant STOP, but it returns "stop" for every input. Explain why, and give two corrected versions. STOP = "red" def act(light): match light: case STOP: return "stop" case _: return "go"
Show answer
Actually, this code does not run. case STOP: is a capture pattern that always matches, and it is followed by case _:, so Python raises a SyntaxError saying the name capture makes the remaining patterns unreachable. If you removed the case _: branch, the function would return "stop" for every input and overwrite STOP. Fix 1: use a literal, case "red":. Fix 2: keep the constant in a class or enum, such as class Light: STOP = "red", and write case Light.STOP:. A guard also works: case l if l == STOP:.
Exercise
Given the code below, what does it print, and how would you stop the caller's list from changing? def addflag(config): match config: case {"flags": flags}: flags.append("debug") settings = {"flags": ["fast"]} addflag(settings) print(settings)
Show answer
It prints {'flags': ['fast', 'debug']}. The capture pattern binds flags to the same list object stored in the dictionary, so append changes the caller's data. To avoid this, copy before modifying, for example flags = list(flags) and then append, or build a new dictionary and return it.