Sub topic 3
Capturing values and the _ wildcard
This chapter covers the two patterns that match any value: the capture pattern and the wildcard _. It assumes you are on Python 3.10 or later and know functions, conditionals, lists, tuples, and * unpacking in assignments. It also assumes you have seen a basic match statement with literal cases. Most other pattern types are built from these two, so it pays to understand their rules exactly.
Two patterns that accept anything
A pattern normally tests the subject, the value after match. Literal patterns such as 200 or "quit" test equality. A capture pattern and the wildcard test nothing. They always succeed. They differ in one respect: whether they remember the value.
| Pattern | Matches | Binds a name? |
|---|---|---|
| `x` (any plain name) | Any value | Yes, `x` is set to the value |
| `_` | Any value | No |
| `[x, _]` | A sequence of exactly two items | `x` only |
| `[x, *rest]` | A sequence of one or more items | `x` and `rest` (a list) |
| `[_, *_]` | A sequence of one or more items | Nothing |
Capture patterns
A bare name in a pattern is a capture pattern. It matches any value and binds the name to that value.
def describe(value):
match value:
case 0:
return "zero"
case other:
return f"something else: {other}"
print(describe(0)) # zero
print(describe(42)) # something else: 42For 42, the literal 0 fails. The pattern other always succeeds, so other is set to 42 and the block runs. A capture pattern on its own is called irrefutable, because it cannot fail.
Captures become useful inside larger patterns. The surrounding pattern checks the shape, and the captures pull out the parts you need:
def parse(command):
match command.split():
case []:
return "empty"
case ["move", x, y]:
return f"move to {x},{y}"
case ["say", word, *_]:
return f"say {word}"
case [verb, *_]:
return f"unknown verb {verb}"
print(parse("move 3 4")) # move to 3,4
print(parse("say hi there")) # say hi
print(parse("jump high")) # unknown verb jump
print(parse("")) # emptyIn ["move", x, y] the literal "move" is tested and x and y are captured. The length must be exactly three. Without a star, a sequence pattern requires an exact length.
The wildcard _
The wildcard _ also matches anything, but it binds nothing. Use it when you need a position to exist but do not care about its value.
def second(items):
match items:
case [_, x, *_]:
return x
case _:
return None
print(second([10, 20, 30])) # 20
print(second([10])) # None
print(second("abc")) # NoneThree details are worth noting:
_is not a variable here. You can use it several times in one pattern, as in[_, _, x], which would be an error for a real name.*_is the "ignore the rest" form of a star pattern. It checks that the sequence is long enough without building a list for the extra items.- The last case,
case _:, is the conventional default. It plays the role ofelsein anifchain.
The string "abc" falls through to the default even though it is a sequence of characters. Sequence patterns deliberately do not match str, bytes, or bytearray. The next chapters cover this in more detail.
Capturing a sub-part
Captures work at any depth. Each name in the pattern is bound to the part of the subject at the same position:
def label(pair):
match pair:
case (name, (x, y)):
return f"{name} at {x},{y}"
case _:
return "not a labelled point"
print(label(("home", (3, 4)))) # home at 3,4
print(label(("home", 3))) # not a labelled pointThe second call fails because 3 is not a sequence of two items. The inner pattern (x, y) cannot match it, so the whole case fails and the next one is tried.
Where the diagram fits
Each case asks two questions. Does the shape match? If so, which names get set? The wildcard answers yes to the first and sets nothing. A capture answers yes and sets one name.
The last node matters. If no case matches and you have no wildcard, the match statement does nothing. It does not raise an error. A function that relies on it returns None implicitly.
Rules and restrictions
An irrefutable case must come last
Cases are tried from top to bottom. A capture or wildcard at the top level always matches, so any case after it could never run. Python rejects this when it compiles the code:
def broken(value):
match value:
case other:
return "first"
case 0:
return "never reached"This raises SyntaxError: name capture 'other' makes remaining patterns unreachable. With case _: in the same position the message says "wildcard makes remaining patterns unreachable". Only top-level cases are checked this way. A capture nested inside a pattern, such as [x, 0], is not irrefutable, because the rest of the pattern can still fail.
A name can be bound once per pattern
You cannot use the same capture name twice in one pattern:
match pair:
case [x, x]: # SyntaxError: multiple assignments to name 'x' in pattern
...Python does not treat this as "both items are equal". If you want that check, capture two names and add a guard, such as case [a, b] if a == b:. Guards are covered in a later chapter. _ is exempt from this rule because it never binds.
Names outlive the match
A match statement does not create a new scope. Captured names are ordinary local variables, so they stay available after the statement ends:
match (1, 2):
case (a, b):
pass
print(a, b) # 1 2This also means a capture overwrites any variable that already has that name. If your function has a parameter x and a case says [x, y], the parameter is replaced.
Or-patterns must bind the same names
Alternatives joined with | must each bind the same set of names. case [x, _] | [_, x]: is valid, because both sides bind x. case [x] | [y]: is a SyntaxError, since the body could not know which name exists. Also, an irrefutable alternative must be last, so case _ | 0: is rejected as well.
The most common mistake: expecting a name to compare
A bare name never compares. It always captures. This surprises people who expect a constant to be tested:
LIMIT = 10
def check(n):
match n:
case LIMIT: # captures n into a new LIMIT; always matches
return "at the limit"
case _:
return "other"Here Python raises SyntaxError: name capture 'LIMIT' makes remaining patterns unreachable for the _ case. The pattern LIMIT is a capture, so it matches every value and replaces the constant. To compare against a constant, use a dotted name such as Settings.LIMIT, or a literal. Dotted names get their own chapter.
Choosing between a capture and _
- Use a capture when the body uses the value.
- Use
_when the value is irrelevant. Many linters report unused variables, and_avoids that. - Use
*_rather than*restwhen you never read the remainder. - End most
matchstatements withcase _:that returns a default or raises an error. Silent fall-through is a frequent source of bugs.
Exercise
Write a function first_and_last(items) using match. It should return a tuple (first, last) for a list or tuple with two or more items, return (only, only) for exactly one item, and return None for anything else (including an empty list). Use captures and _/*_ where appropriate.
Show answer
One solution:
def firstandlast(items):
match items:
case [only]:
return (only, only)
case [first, , last]:
return (first, last)
case :
return None
[only] requires exactly one item. `[first, , last] requires at least two, captures the ends, and ignores the middle without building a list. The default case covers empty sequences and non-sequences (including strings). The single-item case must come first, because [first, *, last]` would never match one item anyway, but putting the narrow case first keeps the intent clear.
Exercise
What happens when this code is compiled, and why? How would you fix it so it compares against the number? THRESHOLD = 100 def level(n): match n: case THRESHOLD: return "at threshold" case _: return "other"
Show answer
Python raises a SyntaxError because the bare name THRESHOLD is a capture pattern. It matches every value, so the case _ after it is unreachable. To fix it, compare with a literal (case 100:) or put the constant in a namespace and use a dotted name, for example an Enum member or an attribute of a class or module (case Limits.THRESHOLD:). A dotted name is a value pattern and is compared with ==.