Sub topic 13
Pitfalls: bare names, unreachable cases, and mutable state
This chapter assumes you know the pattern types from earlier chapters: literal, capture, sequence, mapping, class, and value patterns. It also assumes you know how guards work. Three mistakes account for most match bugs: bare names, case order, and state that leaks out of a match.
Bare names capture, they do not compare
A bare name in a pattern always succeeds and binds the subject to that name. It never compares against an existing variable.
RED = 1
match 99:
case RED:
print("matched", RED) # matched 99The case matches even though 99 is not 1, and it overwrites RED. To compare against a constant, use a dotted name such as Color.RED. You can also use a guard such as case c if c == RED.
Unreachable cases
Python rejects an irrefutable pattern (a capture or _) that is followed by other cases. It cannot see that a general pattern shadows a more specific one, so it stays silent in that situation:
def describe(p):
match p:
case [_, *_]:
return "non-empty"
case [1, 2]:
return "one two" # never runs
print(describe([1, 2])) # non-emptyThe first case accepts every non-empty sequence, so the second case can never be reached. The same bug appears with class patterns. Point() placed before Point(x=0, y=0) hides the more specific case.
Put the most specific patterns first and the general ones last:
- Literals and exact shapes.
- Patterns with guards.
- Broad class or sequence patterns.
- The
_wildcard.
If no case matches and there is no _, nothing happens and no error is raised. A forgotten default fails silently.
Mutable state
Matching can change what your program remembers in three ways.
Names stay bound after the match. Captured names are ordinary variables in the enclosing scope. They are not limited to the case block.
Failed cases may leave bindings behind. A pattern can bind some names before a later part fails. A guard can also fail after its names are bound. Never read a name from a case that did not run:
match [1, 2]:
case [a, 3]:
pass
case [b, c] if c > 5:
pass
# a and b may already be bound here, but do not rely on it.Captures share objects with the subject. A capture binds a reference to the same object, not a copy:
data = {"tags": ["a"]}
match data:
case {"tags": tags}:
tags.append("b")
print(data) # {'tags': ['a', 'b']}Only starred captures such as *rest build a new list. The elements inside it are still shared.
Guards and class patterns can also run your code. A guard that calls a function runs that function every time its case is tried. Property access in class patterns can do the same. Keep guards free of side effects, because you cannot easily predict how often they run.
Exercise
This function should return "stop" for the string "halt" and "go" otherwise. It raises a SyntaxError. Why, and how do you fix it? COMMAND = "halt" def act(word): match word: case COMMAND: return "stop" case _: return "go"
Show answer
case COMMAND: is a capture pattern. It matches anything and binds word to the name COMMAND, so it makes case _ unreachable and Python rejects it. Fix it by comparing instead of capturing. Either use a literal, case "halt":, or use a guard, case w if w == COMMAND:. A dotted name such as Commands.HALT on an enum or class also works.