Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python Capture Pattern: Syntax and Usage

Learn how Python capture patterns bind values to names in match statements, including sequence and class examples, wildcard behavior, and common pitfalls.

~3 min readPython
#python#structural pattern matching#match statement#capture pattern
Illustration of Python capture pattern binding a value from a match statement to a variable.

Python's structural pattern matching, introduced in Python 3.10, includes capture patterns that bind matched values to variable names. A capture pattern looks like a bare name inside a case clause, such as case x:. When the pattern matches, Python assigns the subject value to that name, making it available in the current scope. The syntax is straightforward, but its behavior has subtle implications for variable binding and pattern ordering.

Basic Syntax and Binding Behavior

A capture pattern is simply a name that appears in a pattern. For example:

python
match command: case "start": print("Starting") case other: print(f"Unknown command: {other}")

Here, other is a capture pattern. It matches any value and binds that value to the variable other. Python does not create a separate scope for each case block; the name is bound in the containing scope when that case matches. As with assignment, the variable does not need to exist beforehand, but a bare name in a pattern never compares against an existing variable.

Capture patterns can appear at the top level or nested inside larger patterns, such as sequence patterns, mapping patterns, and class patterns. In each position, the name receives the matched value.

Capturing Multiple Values in Sequence Patterns

Sequence patterns allow you to capture individual elements. For example:

python
point = (3, 4) match point: case (x, y): print(f"x={x}, y={y}")

Here, x and y are capture patterns that bind to the first and second elements of the tuple. The pattern requires exactly two elements; if the sequence has a different length, the case does not match. You can combine capture patterns with literal values:

python
match point: case (0, y): print(f"On y-axis at y={y}") case (x, 0): print(f"On x-axis at x={x}") case (x, y): print(f"Point at ({x}, {y})")

This lets you extract values while still enforcing specific structure.

Using Capture Patterns with Class Patterns

Class patterns match against an object's type and can capture attributes. For example:

python
class Point: def __init__(self, x, y): self.x = x self.y = y match obj: case Point(x=x_val, y=y_val): print(f"Point at ({x_val}, {y_val})")

The names on the left of = are the actual attribute names of the class, and the right side is the capture pattern that binds the value. You can also use positional patterns if the class defines __match_args__.

Wildcard and Ignoring Values

The wildcard pattern _ is a special case: it matches any value but does not bind it. This is useful when you need to match a structure but ignore certain elements. For example:

python
match record: case (name, _, age): print(f"{name} is {age} years old")

Within a pattern, _ is always treated as a wildcard, so it does not create a variable in that context. If you need to bind a value but want to indicate that it is intentionally unused, you can use a name like _unused; unlike _, that name is a capture pattern and will bind the value.

Common Mistakes and Pitfalls

One common mistake is using the same capture name multiple times in a single pattern. Python does not allow repeated capture names; each name must be unique within a pattern. For example, case (x, x): raises a SyntaxError because the same variable would be captured twice. This is different from some other languages where repeated names imply equality.

Another pitfall is confusing capture patterns with literal values. A bare name always captures; it never compares against an existing variable. If you want to match against a value stored in a variable, you need a guard or, when the value is available as an attribute, a dotted value pattern. For example:

python
expected = 5 match value: case _ if value == expected: print("matched expected")

Here, _ matches any value, and the guard value == expected restricts the case.

Pattern Order and Runtime Behavior

Case clauses are checked in order, and the first matching clause is used. A capture pattern such as case (x, y) matches a two-element sequence pattern, so more specific cases must appear before it. For example, put case (0, y) before case (x, y); otherwise the general case captures the value first, and the specific case can never be reached.

When to Use Capture Patterns vs. Regular Assignment

Capture patterns are most valuable when you need to destructure data based on its shape or type. They can replace verbose isinstance checks and manual attribute access. However, for simple variable assignment, a regular assignment is clearer. Use capture patterns when you are already using match to dispatch on structure.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.