Sub topic 11
Positional patterns and `__match_args__`
This chapter assumes you know class patterns with keyword attributes, such as Point(x=0, y=0). It also assumes you know how to define a dataclass. You need Python 3.10 or later.
Why positional patterns need help
A keyword pattern names each attribute: Point(x=0, y=5). A positional pattern drops the names: Point(0, 5). This is shorter, but Python has to know which attribute the first position refers to. A class declares that with a class attribute called __match_args__, a tuple of attribute names.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
print(Point.__match_args__) # ('x', 'y')The @dataclass decorator generated this tuple from the field order. Each positional sub-pattern is then treated as a keyword sub-pattern, using the name at the same index.
Using positional patterns
With the Point class above, these two cases are equivalent:
def label(p):
match p:
case Point(0, 0):
return "origin"
case Point(x, 0):
return f"on the x axis at {x}"
case Point(x, y):
return f"at {x},{y}"
case _:
return "not a point"
print(label(Point(0, 0))) # origin
print(label(Point(4, 0))) # on the x axis at 4
print(label(Point(1, 2))) # at 1,2Point(x, 0) means Point(x=x, y=0). The first x is the attribute name taken from __match_args__. The second is the new variable that captures the value.
Defining `__match_args__` yourself
Dataclasses and named tuples get __match_args__ automatically. A plain class does not, so you write it:
class Vec:
__match_args__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
def describe(v):
match v:
case Vec(0, 0):
return "zero"
case Vec(x, 0):
return f"horizontal {x}"
case Vec(x, y):
return f"vector {x},{y}"
case _:
return "not a vector"
print(describe(Vec(3, 0))) # horizontal 3Without the tuple, Vec(x, y) fails with a TypeError, because Python cannot map positions to names.
Common errors
Too many positional sub-patterns raise an error. They do not simply fail to match:
try:
match Vec(1, 2):
case Vec(a, b, c):
pass
except TypeError as e:
print(type(e).__name__) # TypeErrorThe tuple only covers the first two attributes, so a third position has no name.
You can mix both styles. Positional sub-patterns must come first, as in function calls: Vec(x, y=0). Naming the same attribute twice, once by position and once by keyword, is also an error.
Other situations to know about:
- Dataclass fields declared with
kw_only=Trueare left out of__match_args__. Match them by keyword. @dataclass(match_args=False)suppresses generation of the tuple.- Order matters. If you reorder dataclass fields, every positional pattern changes meaning silently. Keyword patterns survive reordering.
- A few built-in types accept one positional sub-pattern that matches the whole subject. Examples are
int,str,float,listanddict. Incase str(s),sis bound to the subject itself.
Summary
| Pattern | Meaning with `__match_args__ = ("x", "y")` |
|---|---|
| `Vec(1, 2)` | `isinstance`, then `x == 1` and `y == 2` |
| `Vec(a, b)` | `isinstance`, then bind `x` to `a` and `y` to `b` |
| `Vec(a, y=0)` | Mixed. The positional part comes first |
| `Vec(a, b, c)` | `TypeError`, too many positions |
Exercise
A class Rect has __match_args__ = ("w", "h"). Write a case that matches a Rect with equal width and height and binds the side to s. What does Rect(1, 2, 3) do in a case?
Show answer
Use a positional capture and a guard: case Rect(s, h) if s == h:. The Rect(1, 2, 3) pattern raises a TypeError, because __match_args__ lists only two attribute names.