Python pattern match
last modified November 17, 2026 Python 3.15
In this article we show how to use structural pattern matching in Python.
Pattern matching is done with the match statement and its
case blocks. It was added in Python 3.10 (PEP 634). A
match statement takes a value, called the subject,
and compares it against the patterns of the case blocks from top
to bottom. The block of the first matching pattern is executed, and the rest
are skipped; there is no fall-through as in the switch
statements of C or Java. If no pattern matches, nothing happens.
Pattern matching is more than a switch statement. A pattern can
check the type and the structure of the subject and extract parts of it into
variables at the same time. We can match sequences by their length and
elements, dictionaries by their keys, and objects by their class and
attributes.
The match, case, and _ names are soft
keywords: they have a special meaning only in the match
statement, so existing code that uses match as a variable name,
such as the result of re.match, still works.
Literal patterns
In the first example, we match strings against literal values.
langs = ['russian', 'slovak', 'german', 'swedish', 'hungarian', 'french',
'spanish', 'finnish']
for lang in langs:
match lang:
case 'russian':
print('привет')
case 'hungarian':
print('szia')
case 'french':
print('salut')
case 'spanish':
print('hola')
case 'slovak':
print('ahoj')
case 'german':
print('hallo')
case 'swedish':
print('hallå')
case _:
print(f'no greeting for {lang}')
We go through a list of languages and say hello in each of them. The
subject lang is compared with each string literal in turn.
case _:
print(f'no greeting for {lang}')
The wildcard pattern _ matches anything. It is used
as the last, default case; here it handles the language we have no greeting
for. Without it, the finnish value would silently match nothing.
$ python greetings.py привет ahoj hallo hallå szia salut hola no greeting for finnish
OR patterns
Several alternatives are combined into one pattern with the |
operator. The pattern matches if any of the alternatives matches.
grades = ['A', 'B', 'C', 'D', 'E', 'FX', 'X']
for grade in grades:
match grade:
case 'A' | 'B' | 'C' | 'D' | 'E':
print(f'{grade}: passed')
case 'FX':
print(f'{grade}: failed')
case _:
print(f'{grade}: invalid grade')
The grades A through E pass the exam, FX fails it, and anything else is not a valid grade.
$ python grades.py A: passed B: passed C: passed D: passed E: passed FX: failed X: invalid grade
Literals, None, and booleans
Numbers and strings in literal patterns are compared with ==.
The None, True, and False singletons
are compared with is.
def describe(status):
match status:
case 200 | 201 | 204:
return 'success'
case 301 | 302 | 307 | 308:
return 'redirect'
case 404:
return 'not found'
case 500:
return 'server error'
case None:
return 'no response'
case True | False:
return 'not a status code'
case code:
return f'other status {code}'
for status in (200, 204, 302, 404, 418, None, True, 200.0):
print(f'{status!r:6} -> {describe(status)}')
The function describes HTTP status codes. Its last case is a capture pattern: a bare name that matches any value and binds it to the name. It works as a wildcard that also gives us the value.
The output shows the difference between equality and identity. The
200.0 float matches the 200 literal, because
200.0 == 200. The True value does not match any
number literal and reaches the True | False case; it would also
match a 1 literal, because True == 1.
$ python http_status.py 200 -> success 204 -> success 302 -> redirect 404 -> not found 418 -> other status 418 None -> no response True -> not a status code 200.0 -> success
Irrefutable patterns
A capture pattern or a wildcard always succeeds; such a pattern is
irrefutable. Python rejects a match statement where
an irrefutable pattern is followed by other cases, because they could never
be reached.
source = '''
match command:
case action:
print(action)
case 'quit':
print('bye')
'''
try:
compile(source, 'capture.py', 'exec')
except SyntaxError as e:
print(f'{e.msg} (line {e.lineno})')
We compile a piece of code where the case action: capture
pattern comes before a literal pattern. The compiler reports a
SyntaxError.
$ python capture.py name capture 'action' makes remaining patterns unreachable (line 3)
Value patterns
A bare name in a pattern is always a capture pattern, never a reference to a
constant. To compare the subject with a named constant, the name must be
dotted, such as Color.RED or math.pi. This is a
value pattern, and it is compared with ==.
from enum import Enum
class Color(Enum):
RED = 'red'
GREEN = 'green'
BLUE = 'blue'
RED = Color.RED
def wrong(color):
match color:
case RED:
return f'red (RED is now {RED!r})'
def right(color):
match color:
case Color.RED:
return 'red'
case Color.GREEN | Color.BLUE:
return 'not red'
print(wrong(Color.BLUE))
print(right(Color.BLUE))
print(right(Color.RED))
The wrong function intends to check for the red colour with the
RED constant. Instead, case RED captures any value
and rebinds the local name RED, so the blue colour is reported
as red. Had the function another case after it, the compiler would reject it
with the makes remaining patterns unreachable error. The
right function uses the dotted Color.RED name,
which is a value pattern.
$ python colors.py red (RED is now <Color.BLUE: 'blue'>) not red red
Matching enums
Enumeration members are accessed with dotted names, so they work as value patterns. Pattern matching and enums go together well.
from enum import Enum
class Day(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
def day_type(day):
match day:
case Day.SATURDAY | Day.SUNDAY:
return 'weekend'
case Day.FRIDAY:
return 'almost weekend'
case _:
return 'workday'
for day in Day:
print(f'{day.name.capitalize():9} {day_type(day)}')
We define a Day enumeration and classify each day as a workday,
the almost weekend Friday, or the weekend. Iterating over the
Day class yields its members in definition order.
$ python days.py Monday workday Tuesday workday Wednesday workday Thursday workday Friday almost weekend Saturday weekend Sunday weekend
Guards
A guard is an if clause after a pattern. The case
matches only if the pattern matches and the guard expression is true. If the
guard fails, matching continues with the next case.
def classify(n):
match n:
case 0:
return 'zero'
case int() if n < 0:
return 'negative'
case int() if n % 2 == 0:
return 'positive even'
case int():
return 'positive odd'
case _:
return 'not an integer'
for value in (-7, 0, 4, 9, 2.5):
print(f'{value:>4}: {classify(value)}')
The int() class pattern checks that the subject is an integer;
the guards then test its sign and parity. The 2.5 float fails
all int() patterns and reaches the wildcard.
$ python guards.py -7: negative 0: zero 4: positive even 9: positive odd 2.5: not an integer
Sequence patterns
A sequence pattern is written with square brackets or parentheses
and matches a sequence of the given length, element by element. A starred
name, such as *rest, matches any number of remaining elements;
only one starred name is allowed in a pattern.
def describe(seq):
match seq:
case []:
return 'empty'
case [x]:
return f'one element: {x}'
case [x, y]:
return f'two elements: {x}, {y}'
case [first, *_, last]:
return f'{len(seq)} elements from {first} to {last}'
case _:
return 'not a sequence pattern'
for seq in ([], [7], (3, 4), [1, 2, 3, 4, 5], 'ab', range(3), {1, 2}):
print(f'{seq!r:16} {describe(seq)}')
The function describes sequences by their length. The [first, *_,
last] pattern matches sequences of two or more elements, but the
two-element case is caught by the earlier [x, y] pattern.
Lists, tuples, and ranges match sequence patterns. Strings, bytes, and
bytearrays do not, even though they are sequences: treating
'ab' as ['a', 'b'] would be a common source of
bugs. Sets are not sequences at all.
$ python sequences.py
[] empty
[7] one element: 7
(3, 4) two elements: 3, 4
[1, 2, 3, 4, 5] 5 elements from 1 to 5
'ab' not a sequence pattern
range(0, 3) 3 elements from 0 to 2
{1, 2} not a sequence pattern
Parsing commands
Sequence patterns are a natural fit for simple command parsers. We split a command into words and match the resulting list.
def run(command):
match command.split():
case ['look']:
return 'You see a dark corridor.'
case ['go', direction]:
return f'You go {direction}.'
case ['take', item, 'and', other]:
return f'You take the {item} and the {other}.'
case ['take', *items] if items:
return f'You take: {", ".join(items)}.'
case ['quit' | 'exit']:
return 'Bye.'
case []:
return 'Say something.'
case [verb, *_]:
return f'I do not know how to {verb}.'
commands = ['look', 'go north', 'take lamp and key', 'take coin rope map',
'take', 'exit', '', 'dance wildly']
for cmd in commands:
print(f'{cmd!r:22} {run(cmd)}')
Each case describes the shape of one command. The ['go',
direction] pattern matches exactly two words where the first is
go. The ['take', *items] if items case needs at
least one item; a lone take falls through to the generic
[verb, *_] case. The ['quit' | 'exit'] pattern
uses an OR pattern inside a sequence pattern.
$ python commands.py 'look' You see a dark corridor. 'go north' You go north. 'take lamp and key' You take the lamp and the key. 'take coin rope map' You take: coin, rope, map. 'take' I do not know how to take. 'exit' Bye. '' Say something. 'dance wildly' I do not know how to dance.
AS patterns
An OR pattern inside a larger pattern does not bind the matched alternative.
The as keyword binds the value matched by a subpattern to a
name.
def move(command):
match command.split():
case ['go', ('north' | 'south' | 'east' | 'west') as direction]:
return f'moving {direction}'
case ['go', _]:
return 'unknown direction'
case ['go', *rest] as words:
return f'too many words: {words}'
for cmd in ('go north', 'go west', 'go up', 'go north quickly'):
print(f'{cmd!r:18} {move(cmd)}')
The ('north' | 'south' | 'east' | 'west') as direction
subpattern accepts only the four directions and binds the matched one. The
as words clause at the end of the last pattern binds the whole
subject.
$ python as_patterns.py 'go north' moving north 'go west' moving west 'go up' unknown direction 'go north quickly' too many words: ['go', 'north', 'quickly']
Mapping patterns
A mapping pattern matches dictionaries and other mappings. It
checks that the listed keys are present and matches their values against
subpatterns. Unlike sequence patterns, mapping patterns ignore extra keys;
**rest collects them into a new dictionary.
events = [
{'type': 'click', 'x': 120, 'y': 45, 'button': 'left'},
{'type': 'key', 'key': 'Enter', 'mods': ['ctrl']},
{'type': 'key', 'key': 'a'},
{'type': 'resize', 'size': {'width': 800, 'height': 600}},
{'type': 'scroll', 'delta': -3, 'ts': 1700000000},
{'kind': 'click'},
]
for event in events:
match event:
case {'type': 'click', 'x': x, 'y': y}:
print(f'click at ({x}, {y})')
case {'type': 'key', 'key': key, 'mods': [*mods]}:
print(f'key {"+".join(mods + [key])}')
case {'type': 'key', 'key': key}:
print(f'key {key}')
case {'type': 'resize', 'size': {'width': w, 'height': h}}:
print(f'resize to {w}x{h}')
case {'type': kind, **rest}:
print(f'unhandled {kind} event, other keys: {rest}')
case _:
print(f'invalid event: {event}')
We dispatch user interface events represented as dictionaries, such as those
decoded from JSON. Values can be matched by nested patterns: the
[*mods] sequence pattern requires a list of modifiers, and the
{'width': w, 'height': h} pattern looks inside a nested
dictionary. The order of the cases matters: the key event with modifiers must
come before the plain key event, which would match it as well.
$ python mappings.py
click at (120, 45)
key ctrl+Enter
key a
resize to 800x600
unhandled scroll event, other keys: {'delta': -3, 'ts': 1700000000}
invalid event: {'kind': 'click'}
Class patterns with built-in types
A class pattern such as int() checks the type of the
subject with isinstance. For a group of built-in types,
including bool, int, float,
str, bytes, list,
tuple, and dict, a single positional subpattern
matches the subject itself, so int(n) checks the type and binds
the value.
def kind(value):
match value:
case bool(b):
return f'boolean {b}'
case int(n):
return f'integer {n}'
case float() | complex():
return f'other number {value}'
case str(s) if not s:
return 'empty string'
case str(s):
return f'string of length {len(s)}'
case list() | tuple():
return f'sequence of {len(value)} items'
case dict():
return f'dict with keys {list(value)}'
case _:
return f'something else: {type(value).__name__}'
for value in (True, 42, 3.5, 2j, '', 'falcon', [1, 2], (1, 2, 3), {'a': 1}, None):
print(f'{value!r:10} {kind(value)}')
The function describes values by their type. The bool case must
come before the int case, because bool is a
subclass of int and int(n) would also match
True. The complex type is not in the special group,
so complex(x) raises a TypeError; we use
complex() without a subpattern and refer to the subject
itself.
$ python builtin_types.py
True boolean True
42 integer 42
3.5 other number 3.5
2j other number 2j
'' empty string
'falcon' string of length 6
[1, 2] sequence of 2 items
(1, 2, 3) sequence of 3 items
{'a': 1} dict with keys ['a']
None something else: NoneType
Class patterns with dataclasses
A class pattern can match attributes of an object. Keyword subpatterns, such
as Person(name=name), match the named attributes. Positional
subpatterns are mapped to attributes through the class's
__match_args__ tuple, which data classes generate from their
fields.
from dataclasses import dataclass
@dataclass
class Cat:
name: str
age: int
@dataclass
class Dog:
name: str
age: int
@dataclass
class Person:
name: str
occupation: str
data = [Cat('Missy', 3), Dog('Jasper', 9), Dog('Ace', 1),
Person('Peter', 'teacher'), 'Jupiter']
for e in data:
match e:
case Cat(name, age) | Dog(name, age) if age < 2:
print(f'{name} is a young pet')
case Cat(name) | Dog(name):
print(f'{name} is a pet')
case Person(name=name, occupation=job):
print(f'{name} is a {job}')
case _:
print(f'unknown: {e!r}')
We have three classes: Cat, Dog, and
Person. In Cat(name, age), the positional
subpatterns bind the name and age attributes, the
first two fields of the data class.
case Cat(name, age) | Dog(name, age) if age < 2:
print(f'{name} is a young pet')
All alternatives of an OR pattern must bind the same names. The guard
applies to the whole OR pattern, whichever alternative matched. The string
'Jupiter' is not an instance of any of the classes and reaches
the wildcard.
$ python objects.py Missy is a pet Jasper is a pet Ace is a young pet Peter is a teacher unknown: 'Jupiter'
Points and quadrants
In the next example, we use class patterns with keyword subpatterns and guards to place points in a coordinate system.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def where(p):
match p:
case Point(x=0, y=0):
return 'origin'
case Point(x=_, y=0):
return 'on the x axis'
case Point(x=0):
return 'on the y axis'
case Point(x, y) if x > 0 and y > 0:
return 'quadrant I'
case Point(x, y) if x < 0 < y:
return 'quadrant II'
case Point(x, y) if x < 0 and y < 0:
return 'quadrant III'
case Point():
return 'quadrant IV'
case _:
return 'not a point'
points = [Point(3, 0), Point(0, 0), Point(-4, -5), Point(0, 5),
Point(4, 8), Point(-5, 3), Point(6, -4), (1, 2)]
for p in points:
print(f'{p!r:20} {where(p)}')
The Point(x=0, y=0) pattern matches the origin. The
Point(x=0) pattern ignores the y attribute. The
quadrants are decided by guards on the captured coordinates. When the cases
before it have excluded the axes and three quadrants, the bare
Point() pattern matches the remaining points of quadrant IV. A
tuple is not a Point, even if it has two numbers.
$ python points.py Point(x=3, y=0) on the x axis Point(x=0, y=0) origin Point(x=-4, y=-5) quadrant III Point(x=0, y=5) on the y axis Point(x=4, y=8) quadrant I Point(x=-5, y=3) quadrant II Point(x=6, y=-4) quadrant IV (1, 2) not a point
Custom classes and __match_args__
For a regular class, we define the __match_args__ class
attribute ourselves to allow positional subpatterns. Without it, only
keyword subpatterns can be used.
class Temperature:
__match_args__ = ('value', 'unit')
def __init__(self, value, unit='C'):
self.value = value
self.unit = unit
def __repr__(self):
return f'{self.value} {self.unit}'
def comment(temp):
match temp:
case Temperature(v, 'F'):
return comment(Temperature(round((v - 32) * 5 / 9, 1)))
case Temperature(v, 'C') if v >= 30:
return f'hot ({v} C)'
case Temperature(v, 'C') if v <= 0:
return f'freezing ({v} C)'
case Temperature(v, 'C'):
return f'mild ({v} C)'
case Temperature(unit=unit):
return f'unknown unit {unit}'
for t in (Temperature(31), Temperature(90, 'F'), Temperature(-5),
Temperature(20, 'F'), Temperature(18), Temperature(300, 'K')):
print(f'{t!r:8} {comment(t)}')
print(Temperature.__match_args__)
The Temperature class lists its value and
unit attributes in __match_args__, so
Temperature(v, 'C') binds the value and requires the Celsius
unit. Fahrenheit values are converted and passed to a recursive call. The
last case uses a keyword subpattern to report unknown units.
$ python match_args.py
31 C hot (31 C)
90 F hot (32.2 C)
-5 C freezing (-5 C)
20 F freezing (-6.7 C)
18 C mild (18 C)
300 K unknown unit K
('value', 'unit')
Nested patterns
Patterns can be nested to any depth. A class pattern can contain other class patterns, sequence patterns, or literals, and the whole structure is checked in one step.
import math
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
@dataclass
class Circle:
center: Point
radius: float
@dataclass
class Rectangle:
top_left: Point
bottom_right: Point
def area(shape):
match shape:
case Circle(_, r) if r < 0:
raise ValueError(f'negative radius: {r}')
case Circle(radius=r):
return math.pi * r ** 2
case Rectangle(Point(x1, y1), Point(x2, y2)):
return abs(x2 - x1) * abs(y2 - y1)
case _:
raise TypeError(f'unknown shape: {shape!r}')
def at_origin(shape):
match shape:
case Circle(Point(0, 0), _) | Rectangle(Point(0, 0), _):
return True
case _:
return False
shapes = [Circle(Point(0, 0), 2), Rectangle(Point(1, 5), Point(4, 1)),
Rectangle(Point(0, 0), Point(3, 3))]
for s in shapes:
print(f'{type(s).__name__:9} area={area(s):6.2f} at origin={at_origin(s)}')
for bad in (Circle(Point(1, 1), -1), Point(1, 2)):
try:
area(bad)
except (ValueError, TypeError) as e:
print(f'{type(e).__name__}: {e}')
The Rectangle(Point(x1, y1), Point(x2, y2)) pattern
destructures a rectangle and both its corner points at once. The
Circle(Point(0, 0), _) | Rectangle(Point(0, 0), _) pattern
checks whether a shape is anchored at the origin. Unexpected input is
reported with an exception from the wildcard case rather than ignored.
$ python shapes.py Circle area= 12.57 at origin=True Rectangle area= 12.00 at origin=False Rectangle area= 9.00 at origin=True ValueError: negative radius: -1 TypeError: unknown shape: Point(x=1, y=2)
Evaluating expression trees
Pattern matching shines when working with tree structures. In this example, arithmetic expressions are nested tuples, and a recursive function evaluates them.
def evaluate(expr):
match expr:
case int() | float():
return expr
case ('neg', operand):
return -evaluate(operand)
case ('+', left, right):
return evaluate(left) + evaluate(right)
case ('-', left, right):
return evaluate(left) - evaluate(right)
case ('*', left, right):
return evaluate(left) * evaluate(right)
case ('/', left, right):
divisor = evaluate(right)
if divisor == 0:
raise ZeroDivisionError('division by zero in expression')
return evaluate(left) / divisor
case (op, *args):
raise ValueError(f'unknown operator {op!r} with {len(args)} args')
case _:
raise ValueError(f'invalid expression {expr!r}')
exprs = [
('+', 2, ('*', 3, 4)),
('-', ('/', 10, 4), ('neg', 1.5)),
('*', ('+', 1, 2), ('+', 3, ('neg', 4))),
('^', 2, 8),
('/', 1, ('-', 2, 2)),
]
for expr in exprs:
try:
print(f'{expr} = {evaluate(expr)}')
except (ValueError, ZeroDivisionError) as e:
print(f'{expr}: {e}')
Numbers evaluate to themselves. A tuple with an operator and one or two
operands is matched by its operator and length; the operands are evaluated
recursively. The (op, *args) case catches unknown operators.
$ python calculator.py
('+', 2, ('*', 3, 4)) = 14
('-', ('/', 10, 4), ('neg', 1.5)) = 4.0
('*', ('+', 1, 2), ('+', 3, ('neg', 4))) = -3
('^', 2, 8): unknown operator '^' with 2 args
('/', 1, ('-', 2, 2)): division by zero in expression
Validating JSON data
Mapping patterns combined with class patterns validate data structures, such as parsed JSON, and extract their values at the same time.
import json
text = '''
[
{"name": "web", "port": 8080, "tls": {"cert": "web.pem"}},
{"name": "db", "port": "5432"},
{"name": "cache", "port": 6379, "replicas": [1, 2, 3]},
{"name": "queue"},
{"port": 9000}
]
'''
for service in json.loads(text):
match service:
case {'name': str(name), 'port': int(port), 'tls': {'cert': cert}}:
print(f'{name}: https on {port} with {cert}')
case {'name': str(name), 'port': int(port), 'replicas': [_, _, *_] as r}:
print(f'{name}: port {port}, {len(r)} replicas')
case {'name': str(name), 'port': int(port)}:
print(f'{name}: port {port}')
case {'name': str(name), 'port': port}:
print(f'{name}: invalid port {port!r}')
case {'name': str(name)}:
print(f'{name}: missing port')
case _:
print(f'invalid entry: {service}')
Each service entry needs a string name and an integer port. The
int(port) pattern rejects the port given as the string
"5432", which a plain capture pattern would accept. The
[_, _, *_] as r pattern requires a list of at least two
replicas.
$ python json_config.py
web: https on 8080 with web.pem
db: invalid port '5432'
cache: port 6379, 3 replicas
queue: missing port
invalid entry: {'port': 9000}
When nothing matches
The match statement is not an expression and returns no value.
When no case matches, the statement does nothing and the program continues.
Names bound by the matching case are ordinary local variables and remain
available after the statement.
def parse(token):
match token:
case 'yes' | 'y':
result = True
case 'no' | 'n':
result = False
case other:
raise ValueError(f'expected yes or no, got {other!r}')
return result
def silent(token):
match token:
case 'yes':
print('matched yes')
print(f'after match with {token!r}')
print(parse('y'))
print(parse('no'))
try:
parse('maybe')
except ValueError as e:
print(e)
silent('nope')
The parse function sets the result variable in the
cases and returns it after the match statement. Invalid input is
captured by the other name and reported with an exception. The
silent function shows that an unmatched subject is not an error.
When all values must be handled, raise an exception in a final wildcard case.
$ python no_match.py True False expected yes or no, got 'maybe' after match with 'nope'
Source
The match statement – Python language reference
PEP 636 – Structural Pattern Matching: Tutorial
PEP 634 – Structural Pattern Matching: Specification
In this article we have worked with structural pattern matching in Python. See also Python enum, Python dataclass, and Python control flow.
Author
List all Python tutorials.