Branch on structured input
Dispatch based on a value or shape while keeping alternatives explicit.
Python · Const
The match statement performs structural pattern matching by testing a subject against ordered case patterns. It executes the first successful case, optionally subject to a guard.
Python evaluates the subject expression, then tests each case pattern in order. A successful pattern can bind values; an optional guard is checked afterward, and the case body runs only when the guard is true.
match subject_expr:
case patterns [if guard]:
suite| Name | Type | Description |
|---|---|---|
subject_expr | expression | Expression whose resulting value is tested against the case patterns. |
patterns | pattern | Pattern tested against the subject; it may include subpatterns and bindings. |
guard | if expression | Optional condition evaluated after the pattern succeeds. |
A match statement does not produce a value; it executes the first case block whose pattern succeeds and whose guard, if present, is true.
def describe(value):
match value:
case 0:
return "zero"
case [first, *rest]:
return f"list starting with {first}"
case _:
return "other"
print(describe([1, 2, 3]))This runnable example uses literal, sequence, and wildcard patterns; the first successful case returns its description.
Dispatch based on a value or shape while keeping alternatives explicit.
Extract fields from tuples, sequences, mappings, or objects during dispatch.
Add an if condition after structural matching to refine a branch.
A match statement evaluates one subject and compares it with successive case patterns. It executes the body of the first successful case, optionally after checking that case's guard.
Follow-up: How can a pattern extract data? Use capture patterns, sequence patterns, or object patterns; successful matches bind the extracted values to names.
A guard is an optional if condition attached to a case. Python evaluates it only after the pattern succeeds, with the pattern's bindings available.
Follow-up: What happens when the guard is false? Python proceeds to try the next case block.
A subject expression containing a comma is turned into a tuple using normal tuple-construction rules. Patterns can then compare or unpack that resulting value.
Follow-up: What syntax supports alternatives? The | pattern combines alternatives, allowing one case to accept multiple pattern forms.
caseguardpatternssequence patternsmapping patternsclass patternsliteral patternswildcard pattern