Sub topic 11
Positional patterns and __match_args__
This chapter assumes you know keyword class patterns such as Point(x=0, y=0). It also assumes you know dataclasses and the difference between a capture name and a literal. You need Python 3.10 or later.
From keyword to positional
A class pattern can name attributes: Point(x=0, y=0). It can also give the sub-patterns by position: Point(0, 0). The positional form is shorter. It works only if Python knows which attribute each position means. That information comes from a class attribute named __match_args__.
__match_args__ is a tuple of strings. Each string is an attribute name, and the tuple's order defines the positions. When you write Point(a, b), Python rewrites it internally as Point(x=a, y=b), using the first two names in the tuple.
How Python resolves a positional pattern
For case Point(p1, p2): the interpreter does these steps.
- It checks
isinstance(subject, Point). If this fails, the case does not match. - It reads
Point.__match_args__. - It pairs
p1with the first name andp2with the second name. - It reads each attribute with
getattrand matches the value against the paired sub-pattern.
Dataclasses provide it for free
The @dataclass decorator builds __match_args__ from the parameters of the generated __init__, in field order. That is why the class pattern in an earlier chapter worked with Point(x, y).
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
print(Point.__match_args__) # ('x', 'y')
def describe(p):
match p:
case Point(0, 0):
return "origin"
case Point(x, 0):
return f"on the x axis at {x}"
case Point(0, y):
return f"on the y axis at {y}"
case Point(x, y):
return f"at {x},{y}"
case _:
return "not a point"
print(describe(Point(0, 0))) # origin
print(describe(Point(7, 0))) # on the x axis at 7
print(describe(Point(3, 4))) # at 3,4Literals and captures mix freely inside the parentheses. In Point(x, 0), the 0 is a literal pattern, and x is a capture that binds the value of the x attribute.
Other standard types supply the tuple too:
| Type | Where `__match_args__` comes from |
|---|---|
| `@dataclass` | Fields that are `__init__` parameters, in order. Fields marked `kw_only=True` and fields with `init=False` are left out. |
| `collections.namedtuple` and `typing.NamedTuple` | The field names, in order. |
| Plain class | Nothing. You must define it yourself. |
Defining it on your own class
For an ordinary class, assign a tuple of attribute names. The names do not have to match __init__ parameters. They only have to be attributes the instance can supply, and properties count.
class Version:
__match_args__ = ("major", "minor")
def __init__(self, major, minor, patch=0):
self.major = major
self.minor = minor
self.patch = patch
def check(v):
match v:
case Version(3, minor) if minor >= 10:
return f"modern 3.{minor}"
case Version(3, minor):
return f"old 3.{minor}"
case Version(major):
return f"major {major} only"
case _:
return "not a version"
print(check(Version(3, 12))) # modern 3.12
print(check(Version(2, 7))) # major 2 onlyThe tuple lists only two names, so patch can be matched only by keyword: Version(3, patch=1). You can use fewer positional sub-patterns than the tuple has names, as Version(major) does. You cannot use more.
Errors you will meet
Python reports a mismatch between a pattern and the class at match time, not when the function is defined.
class Plain:
def __init__(self, x):
self.x = x
def try_it(value):
try:
match value:
case Plain(x):
return f"x is {x}"
case _:
return "no match"
except TypeError as error:
return f"TypeError: {error}"
print(try_it(Plain(1)))
# TypeError: Plain() accepts 0 positional sub-patterns (1 given)
print(try_it(42))
# no matchThe second call shows that the isinstance check runs first. If the subject is not a Plain, Python never looks at __match_args__, so no error occurs. The TypeError appears only when an instance reaches the pattern. A test that never passes an instance can therefore hide the mistake.
You also cannot match the same attribute twice. Point(0, x=1) is rejected, because position 0 already means x. Positional sub-patterns must come before keyword ones, as in function calls.
Positional order is part of your API
When you use Point(x, y), you depend on the order of the fields. If someone reorders the dataclass fields to y: int then x: int, every positional pattern silently changes meaning. Point(0, y) would now test the other attribute, and no error is raised.
Keyword patterns do not have this problem. The usual rule is:
- Use positional patterns for small, stable classes whose order everyone knows, such as points, pairs, and tokens.
- Use keyword patterns for classes with many fields, or classes that are likely to change.
Subclasses inherit the tuple. If a subclass adds fields and you want them available by position, redefine __match_args__ in the subclass. A subclass that is a dataclass gets a fresh tuple that includes the inherited fields first.
from dataclasses import dataclass, field
@dataclass
class Config:
host: str
port: int = 80
debug: bool = field(default=False, kw_only=True)
print(Config.__match_args__) # ('host', 'port')
def summary(c):
match c:
case Config("localhost", port):
return f"local on {port}"
case Config(host, port, debug=True):
return f"{host}:{port} (debug)"
case Config(host, port):
return f"{host}:{port}"
print(summary(Config("localhost", 8000))) # local on 8000
print(summary(Config("a.example", debug=True))) # a.example:80 (debug)Because debug is keyword-only, it is not in the tuple. A positional pattern cannot reach it, but the keyword pattern debug=True can.
Built-in types accept one positional argument
For several built-in types, a single positional sub-pattern matches the whole subject instead of an attribute. The types are bool, bytearray, bytes, dict, float, frozenset, int, list, set, str, and tuple. They do not use __match_args__.
def describe_value(v):
match v:
case bool(b):
return f"bool {b}"
case int(n):
return f"int {n}"
case str(s):
return f"str of length {len(s)}"
case [int(a), int(b)]:
return f"pair of ints {a}, {b}"
case _:
return "other"
print(describe_value(True)) # bool True
print(describe_value(5)) # int 5
print(describe_value("hello")) # str of length 5
print(describe_value([1, 2])) # pair of ints 1, 2bool comes first because True is also an int, and cases are tried top to bottom. int(n) is a type check plus a capture. It is a compact way to say "an int, and call it n" inside a larger pattern.
Named tuples
Named tuples define __match_args__ automatically, so positional patterns work with no extra code.
from typing import NamedTuple
class Span(NamedTuple):
start: int
end: int
def length(s):
match s:
case Span(a, b) if b >= a:
return b - a
case Span():
return 0
print(Span.__match_args__) # ('start', 'end')
print(length(Span(2, 9))) # 7Span() with no arguments only checks the type, which makes a good fallback.
Summary of rules
- Positional sub-patterns map to the names in
__match_args__, in order. - Dataclasses and named tuples generate the tuple. Plain classes need it written by hand.
- Too many positional sub-patterns raise
TypeError, but only after theisinstancecheck passes. - Positional patterns break quietly when field order changes, so prefer keywords for volatile classes.
- Built-in types such as
intandstrtake one positional sub-pattern for the whole value.
Exercise
A class Money has __init__(self, amount, currency) and sets self.amount and self.currency, but defines no __match_args__. What happens when match Money(5, "EUR") reaches case Money(a, c):, and how do you fix it in two different ways?
Show answer
Python raises TypeError saying Money() accepts 0 positional sub-patterns (2 given), because the class has no __match_args__. Fix 1: add __match_args__ = ("amount", "currency") to the class. Fix 2: change the pattern to keywords, case Money(amount=a, currency=c):. Turning Money into a dataclass would also work, because it generates the tuple.
Exercise
Given @dataclass class Order: id: int; item: str; qty: int = 1; rush: bool = field(default=False, kw_only=True), write a pattern that matches a rush order with quantity 1 and captures the item name as item.
Show answer
case Order(_, item, 1, rush=True):. The tuple is ('id', 'item', 'qty'), so the wildcard covers id, item captures the second attribute, and 1 is a literal for qty. rush is keyword-only, so it must be given by keyword.