PythonConditional Statements and LoopsPython pattern matching
What is pattern matching using `match-case`?
Question 50 of 88 · Updated
On this page
- 1. Basic syntax and literal patterns
- 2. How matching proceeds
- 3. Common pattern categories
- 4. Sequence patterns and starred captures
- 5. Mapping patterns
- 6. Class patterns and dataclasses
- 7. Guards and the as pattern
- 8. Capture patterns versus value patterns
- 9. Practical example: dispatch structured messages
- 10. Subject evaluation and guard order
- 11. Literal matching and singleton matching
- 12. match-case versus if-elif-else
- 13. Complexity and production considerations
- 14. Common mistakes and syntax errors
- Frequently asked questions
- Which Python version introduced match-case?
- Is match a reserved keyword?
- Does match-case fall through like some switch statements?
- Is case _ mandatory?
- Can match-case unpack a dictionary or an object?
- Can guards use arbitrary conditions?
- Interview-ready answer
- Official references
Structural pattern matching is a control-flow feature that selects a branch by matching a subject against a series of patterns. Python introduced the match and case statement in version 3.10. Unlike an ordinary chain of if statements that evaluates Boolean conditions, a match statement can inspect an object's structure, extract values into names and optionally apply a Boolean guard.
It is particularly useful for processing structured messages, nested data, command variants and objects with several possible shapes.
1. Basic syntax and literal patterns#
PYTHONdef route(action): match action: case 'start' | 'resume': return 'run' case 'stop': return 'halt' case _: return 'unknown' print([route(x) for x in ('start','resume','stop','pause')])
Output:
['run', 'run', 'halt', 'unknown']The subject is action. Each case introduces a pattern and an associated suite. The first pattern uses the OR-pattern syntax to accept either of two literals. The underscore is a wildcard pattern that matches any subject without creating a binding.
Only the suite of the first case with a successful pattern and a truthy guard (if present) is executed. There is no implicit fall-through into subsequent cases. If no case matches, execution continues after the match statement.
A match statement does not itself produce an expression value. The example returns values from a surrounding function.
2. How matching proceeds#
The diagram describes normal completion. A return, break, continue where permitted, or exception can transfer control elsewhere. Guards are evaluated only when the corresponding pattern succeeds; a false guard allows Python to consider later cases.
Matching is not a transaction. A pattern may access attributes or perform comparisons that have side effects. The language intentionally leaves some details of failed partial bindings and internal matching operations unspecified. Do not depend on them.
3. Common pattern categories#
| Pattern example | Meaning |
|---|---|
case 200: | Match a literal value |
case None: | Match the None singleton |
case value: | Capture the subject into a name |
case _: | Match anything without capturing |
case Color.RED: | Match a qualified value |
case [x, y]: | Match a two-element sequence and capture elements |
case [head, *tail]: | Match a nonempty sequence and collect remaining elements |
case {"id": ident}: | Match a mapping with a required key |
case Point(x, y): | Match a class instance and extract fields |
| `case 1 \ | 2:` |
case int() as n if n > 0: | Match a type, capture the object and apply a guard |
A pattern is not an ordinary expression. For instance, the vertical bar in an OR pattern separates alternatives; it does not compute integer bitwise OR. Likewise, a name in a capture pattern introduces a binding rather than comparing the subject with the current value of that name.
4. Sequence patterns and starred captures#
PYTHONdef describe(value): match value: case [x,y]: return ('pair',x,y) case [head,*tail]: return ('many',head,tail) case _: return 'other' print(describe((1,2)), describe([1,2,3]), describe('ab'), describe([]))
Output:
('pair', 1, 2) ('many', 1, [2, 3]) other otherThe first pattern requires a sequence of exactly two elements. Although square brackets are used in the pattern, a tuple can match it. The second pattern requires at least one element, captures the first into head and collects the remaining elements into a list named tail.
Strings, bytes and bytearray are specifically excluded from sequence-pattern matching. An arbitrary iterable or generator does not automatically qualify as a sequence for this purpose. Python determines eligible sequence types through its pattern-matching rules.
The first successful alternative wins, so the exact two-element pattern is placed before the broader nonempty-sequence pattern. Reversing that order would make the pair branch ineffective for ordinary two-element sequences.
Only one starred subpattern is permitted in a sequence pattern. Nested sequence patterns can express more complex shapes without explicit indexing, but a readable helper function may be preferable when a pattern becomes difficult to understand.
5. Mapping patterns#
PYTHONdef event(data): match data: case {'kind':'order','id': ident, **extra}: return ident,extra case _: return None print(event({'kind':'order','id':7,'qty':2})) print(event({'kind':'order'}))
Output:
(7, {'qty': 2})
NoneThe first case requires the mapping to contain kind with the value 'order' and an id key. The value associated with id is captured into ident. The double-star capture collects unmatched entries into a dictionary named extra.
Mapping patterns ordinarily permit additional keys even without a double-star capture. They are not exact-key-set checks. A missing required key makes the pattern fail. Mapping matching uses the defined mapping protocol, including a two-argument get operation for required keys; it is not equivalent to blindly indexing each key and relying on default creation.
For example, a message matching a pattern with an id key might still contain unrecognized fields or an invalid identifier. If the application requires an exact schema, permitted types or range checks, validate those separately.
6. Class patterns and dataclasses#
Class patterns check whether a subject is an instance of a specified class and can match selected attributes.
PYTHONfrom dataclasses import dataclass @dataclass class Point: x:int y:int def classify(p): match p: case Point(0,0): return 'origin' case Point(x=0,y=y): return ('vertical',y) case Point(x,y): return ('point',x,y) case _: return 'other' print(classify(Point(0,0)),classify(Point(0,3)),classify(Point(2,4)))
Output:
origin ('vertical', 3) ('point', 2, 4)Point(0,0) is a class pattern, not a call constructing a new Point. It tests class membership and matches the designated positional attributes.
For ordinary user-defined classes, positional class patterns use the class's __match_args__ contract to map positions to attribute names. The dataclass in the example generates __match_args__ for its ordinary positional initialization fields. Keyword class patterns such as Point(x=0,y=y) explicitly name attributes and do not depend on their positional order.
The check generally follows isinstance semantics, so subclass instances can match. Attribute access can execute descriptors or properties. An AttributeError while retrieving a required attribute makes the class pattern fail; other exceptions can propagate.
Some built-in classes have special support for a single positional subpattern that matches the object itself. Do not assume that every class supports arbitrary positional patterns.
7. Guards and the as pattern#
A guard is a Boolean expression following a pattern. It refines a match using a predicate that cannot conveniently be expressed through the pattern alone.
PYTHONdef category(value): match value: case int() as n if n > 0 and not isinstance(n,bool): return 'positive int' case int(): return 'other int' case _: return 'other' print([category(v) for v in (2,0,True,'2')])
Output:
['positive int', 'other int', 'other int', 'other']The first case checks whether value is an instance of int, captures that object into n, and evaluates the guard. The guard requires a positive integer while excluding bool. The second case illustrates that True can still match int(), because bool is a subclass of int.
An as pattern binds the subject of the enclosed successful pattern to a name. A guard can then inspect that name or call a suitable predicate.
Guards follow ordinary truth-value testing. A false guard does not execute its suite and allows subsequent cases to be considered. Exceptions in guards propagate normally instead of being silently treated as false.
8. Capture patterns versus value patterns#
PYTHONfrom enum import Enum class Color(Enum): RED=1 BLUE=2 match Color.RED: case Color.RED: print('red') case _: print('other') match 7: case captured: print(captured) print(captured)
Output:
red
7
7Color.RED is a qualified value pattern. It compares the subject with the designated enumeration member using the applicable equality rules.
In contrast, a bare name such as captured is a capture pattern. It matches any subject and binds that name. Uppercase spelling alone does not change this behavior. Writing case RED does not normally compare with an existing constant named RED.
An unguarded capture is irrefutable: it cannot fail through pattern matching. A later case after such a pattern is unreachable, and Python rejects the construct with SyntaxError. The wildcard is also irrefutable when unguarded. Put a fallback case at the end.
Successful pattern bindings follow the surrounding scope rules and can outlive the case suite, as shown by the final print. Do not assume all captures have been initialized after a match, especially if a case was not selected. Avoid depending on bindings created during failed partial matches.
9. Practical example: dispatch structured messages#
PYTHONdef process(message): match message: case {'op':'add','amount': int() as n} if type(n) is int and n>0: return ('add',n) case {'op':'add'}: return ('invalid amount',) case {'op':'ping'}: return ('pong',) case _: return ('unknown',) print([process(m) for m in ({'op':'add','amount':3},{'op':'add','amount':True},{'op':'ping'}, {})])
Output:
[('add', 3), ('invalid amount',), ('pong',), ('unknown',)]The function handles an add message with a positive exact integer amount, a malformed add message, a ping message and unrecognized input. The exact-type guard rejects Boolean values.
The more specific add case must precede the broader add case. Otherwise the general case would also match valid add messages.
This is a local dispatch demonstration, not a complete API or authorization layer. Mapping patterns allow extra fields, and the example does not enforce request size limits, authentication, tenant ownership, rate limits or other business rules. Use schema validation and trusted authorization at the actual service boundary.
10. Subject evaluation and guard order#
PYTHONdef subject(): print('subject') return 2 def guard(n): print('guard',n) return False match subject(): case int() as n if guard(n): print('first') case 2: print('second') case _: print('fallback')
Output:
subject
guard 2
secondThe subject expression is evaluated once. The first pattern matches and binds n, but the guard returns False. Python considers the next case, whose literal pattern succeeds. The fallback is skipped.
Do not infer that every comparison or attribute lookup inside a complex pattern occurs exactly once. The language allows implementation choices in parts of the matching protocol. Keep matching properties, equality behavior and guards predictable rather than relying on undocumented side-effect counts.
11. Literal matching and singleton matching#
PYTHONmatch 1: case True: print('true') case 1: print('one') match True: case 1: print('numeric equality')
Output:
one
numeric equalityThe singleton literal patterns None, True and False use identity. Other literal patterns, including integer and string literals, use equality according to the matching rules. Thus case True does not match integer 1, but case 1 can match the Boolean True.
This distinction is related to the earlier equality and identity lessons. A literal integer pattern is not necessarily a strict exact-type test. Use a suitable class pattern and guard when the domain requires exact types.
12. match-case versus if-elif-else#
| Consideration | match-case | if-elif-else |
|---|---|---|
| Primary purpose | Recognize structural alternatives and extract values | Evaluate general Boolean predicates |
| Subject | Evaluated once before cases are considered | Each condition evaluates its own expressions |
| Binding | Capture patterns can bind names | Explicit assignment or assignment expressions |
| Conditions | Optional guards after successful patterns | Arbitrary conditions |
| Best fit | Structured records, object variants, command shapes | Ranges, business predicates, independent comparisons |
| Availability | Python 3.10 and later | All modern Python versions |
Use match when the shape of the input drives the decision. Use if for arbitrary conditions, particularly when no meaningful structure needs to be extracted.
Python structural matching is more powerful than a traditional switch over scalar constants. However, it is not a universal replacement for if statements, and Python does not automatically guarantee exhaustive handling of every possible subject. A wildcard or a deliberate no-match policy helps make the intended behavior explicit.
13. Complexity and production considerations#
For k cases, matching can consider up to k patterns before a suite is selected or the statement ends. For bounded-cost patterns and guards, this gives an O(k) worst-case case-selection cost.
Individual patterns can have additional costs. A starred sequence capture can allocate a list containing many elements. A double-star mapping capture can allocate a dictionary of remaining entries. Class patterns can access attributes, and comparisons or guards may call arbitrary code. The actual time and memory requirements depend on these operations; there is no universal constant-time dispatch guarantee.
For large tables of simple exact identifiers, a dictionary-based dispatch can be a clearer alternative and may offer expected constant lookup cost under ordinary hash-table assumptions. For structured alternatives, match can communicate the decision and extraction together.
Test every relevant input shape, missing field, guard boundary and unknown variant. Validate externally supplied data at an appropriate trust boundary and keep pattern guards simple.
14. Common mistakes and syntax errors#
| Mistake | Explanation |
|---|---|
| Bare constant name in a case | Usually captures instead of comparing; use a qualified value pattern |
| Unguarded wildcard or capture before another case | Irrefutable pattern makes later cases unreachable |
| OR alternatives binding different names | SyntaxError; alternatives must bind the same name set |
| Repeating a capture name in one pattern | SyntaxError; do not use repeated capture to assert equality |
| Assuming a mapping pattern rejects extra keys | It normally accepts additional keys |
| Assuming every iterable matches a sequence pattern | Sequence matching has specific eligibility rules |
| Treating bool as distinct from int in a class pattern | int() can match bool instances |
| Assuming a false guard rolls back all bindings | Do not rely on rollback or failed-match binding details |
Four independent compilation tests confirmed SyntaxError for an unguarded capture followed by a case, an OR pattern with incompatible alternatives, a repeated sequence capture, and an incomplete guard expression.
To test equality between extracted values, capture them into distinct names and compare them in a guard. This expresses the requirement explicitly.
Frequently asked questions#
Which Python version introduced match-case?#
Python 3.10 introduced structural pattern matching. Earlier Python versions cannot parse match statements.
Is match a reserved keyword?#
match and case are soft keywords: they have special meaning in the appropriate pattern-matching grammar context, but can be ordinary identifiers in other contexts.
Does match-case fall through like some switch statements?#
No. Only the first case whose pattern and guard succeed is selected.
Is case _ mandatory?#
No. If no pattern succeeds, execution continues after the match statement. Include an explicit fallback if the application needs default behavior.
Can match-case unpack a dictionary or an object?#
Yes. Mapping patterns match required keys and capture values. Class patterns can match types and extract attributes.
Can guards use arbitrary conditions?#
Yes. A guard is evaluated as an ordinary expression after its pattern matches, subject to normal expression and scope rules.
Interview-ready answer#
Python's match-case statement implements structural pattern matching, introduced in Python 3.10. It evaluates a subject once, tests case patterns in order, binds captured values and optionally evaluates a guard. The first successful pattern with a truthy guard selects its suite; there is no fall-through. Patterns support literals, wildcards, captures, OR alternatives, sequences, mappings and class instances. Unlike a simple switch, structural matching can destructure data. Use it when decisions depend on input structure, and use if-elif-else for general predicates. Be careful with bare-name captures, broad patterns, extra mapping keys and uninitialized bindings.
Official references#
- Python Language Reference — The match statement
- Python Tutorial — match Statements
- PEP 634 — Structural Pattern Matching: Specification
- PEP 635 — Structural Pattern Matching: Motivation and Rationale
- PEP 636 — Structural Pattern Matching: Tutorial
- Python Standard Library — dataclasses
- Python Language Reference — Soft Keywords
Verification note: All nine runnable code groups were executed in independent namespaces on CPython 3.13.5 and matched their documented outputs. Four independent compilation tests raised the expected SyntaxError. The two fenced Mermaid flowcharts were manually reviewed; the local Mermaid CLI was unavailable, so parser validation and public-site rendering remain unverified. Official reference links are supplied under the authorized offline research exception; live documentation and Supabase changelog were not checked.
References
- 1.Python Language Reference — The match statementdocs.python.org
- 2.Python Tutorial — match Statementsdocs.python.org
- 3.PEP 634 — Structural Pattern Matching: Specificationpeps.python.org
- 4.
- 5.PEP 636 — Structural Pattern Matching: Tutorialpeps.python.org
- 6.Python Standard Library — dataclassesdocs.python.org
- 7.Python Language Reference — Soft Keywordsdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design