Sub topic 10
Matching class instances
This chapter assumes you know how to write a match statement with literal, capture, and wildcard patterns. It also assumes you can read dataclasses and know how attributes work. The goal is to match objects by type and by attribute values, and to know what Python does behind the scenes.
The shape of a class pattern
A class pattern looks like a constructor call. It does not call anything. It asks two questions about the subject:
- Is the subject an instance of this class?
- Do the listed attributes exist, and does each one match its sub-pattern?
from dataclasses import dataclass
@dataclass
class Circle:
radius: float
@dataclass
class Rect:
width: float
height: float
def area(shape):
match shape:
case Circle(radius=r):
return 3.14159 * r * r
case Rect(width=w, height=h):
return w * h
case _:
raise TypeError(f"unsupported shape: {shape!r}")
print(area(Circle(2))) # 12.56636
print(area(Rect(3, 4))) # 12In Circle(radius=r), the name r is a capture pattern. It binds the value of shape.radius. The keyword on the left is an attribute name of the subject. The pattern on the right can be any pattern: a literal, a capture, a nested class pattern, and so on.
Keyword patterns in detail
Each keyword pattern reads an attribute from the subject. This has some consequences:
- A literal sub-pattern turns the attribute into a filter:
Circle(radius=0)matches only circles with radius 0. - Attributes you do not list are ignored.
Rect()matches everyRect, whatever its fields. - A missing attribute is not an error. The case fails and Python moves on.
- Any attribute works, not only dataclass fields. Properties and plain instance attributes are read the same way.
Because properties are ordinary attribute reads, they run their code. Do not put side effects in a property that a pattern might read. Also do not rely on how many times, or in what order, Python reads attributes. The language does not promise either.
Matching built-in types
The built-in types work as class patterns too. An empty pair of parentheses checks only the type:
def kind(v):
match v:
case bool():
return "bool"
case int():
return "int"
case str():
return "str"
case _:
return "other"
print(kind(True)) # bool
print(kind(7)) # intOrder matters here. bool is a subclass of int, so True also satisfies int(). Putting bool() first makes the distinction work. The same rule applies to any class hierarchy: isinstance accepts subclasses, so list the more specific class before its parent.
A handful of built-ins (bool, bytearray, bytes, dict, float, frozenset, int, list, set, str, tuple) accept one positional sub-pattern. That pattern is matched against the whole subject. This gives a compact way to check a type and capture the value together:
def double(v):
match v:
case int(n) | float(n):
return n * 2
case str(s):
return s + s
case _:
raise TypeError(f"cannot double {v!r}")
print(double(4)) # 8
print(double("ab")) # ababBoth alternatives in int(n) | float(n) bind the same name n. Python requires every branch of an or-pattern to bind the same set of names.
Nesting class patterns
Sub-patterns can be class patterns themselves, so you can describe a structure several objects deep:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
@dataclass
class Line:
start: Point
end: Point
def describe(shape):
match shape:
case Line(start=Point(x=0, y=0), end=Point(x=x, y=y)):
return f"line from origin to {x},{y}"
case Line(start=Point(y=y1), end=Point(y=y2)) if y1 == y2:
return "horizontal line"
case Line():
return "some other line"
case _:
return "not a line"
print(describe(Line(Point(0, 0), Point(3, 4)))) # line from origin to 3,4
print(describe(Line(Point(1, 2), Point(5, 2)))) # horizontal line
print(describe(Line(Point(1, 2), Point(5, 3)))) # some other lineThe second case uses a guard. Python binds y1 and y2 first and then evaluates the if condition. If the condition is false, the case fails and Python tries the next one. The names stay bound after a failed guard, so do not rely on them being unset.
Mixing positional patterns
Class patterns also accept positional sub-patterns, as in Point(x, y). Positional patterns work for dataclasses because they define __match_args__, a tuple that maps positions to attribute names. The next chapter covers how that works and how to define it for your own classes. For now, remember two facts. Keyword patterns work for any class. Positional patterns need __match_args__, or a built-in type that supports them.
You can combine both styles in one pattern, as long as positional patterns come first: Point(0, y=y).
What a class pattern checks
| Pattern | Checks | Binds | Column |
|---|---|---|---|
| `Point()` | instance of `Point` (or a subclass) | nothing | |
| `Point(x=0)` | instance, and `x` equals 0 | nothing | |
| `Point(x=a, y=b)` | instance, and both attributes exist | `a`, `b` | |
| `Point(x=0) \ | Point(y=0)` | either alternative matches | nothing |
| `Line(start=Point(x=a))` | instance, and `start` is a `Point` with `x` | `a` | |
| `int(n)` | instance of `int` | `n` is the subject |
Pitfalls specific to class patterns
Forgetting the parentheses
case Point: without parentheses is not a class pattern. A bare name is a capture pattern, so it matches anything and binds the subject to a variable called Point. When this case is not the last one, Python raises a SyntaxError ("name capture 'Point' makes remaining patterns unreachable"). When it is last, there is no error. The case silently matches everything and shadows your class name. Always write Point().
Misspelled attribute names
If you write Circle(radious=r), nothing fails loudly. The attribute lookup finds nothing, the case never matches, and execution falls through to a later case. A catch-all case _: hides the mistake. Tests that exercise each branch are the best defence, and a case _: raise ... default makes surprises visible.
Subclasses and order
Because the type check uses isinstance, a pattern for a base class also matches every subclass. A case for the parent placed above a case for the child makes the child case unreachable. Python does not warn about this, because it cannot know the class hierarchy at compile time. Order cases from most specific to most general.
Patterns that are not classes
The name before the parentheses must refer to a class. Using a function or instance there raises a TypeError when the pattern is tried. Dotted names such as shapes.Circle() are fine, so you can match classes from imported modules without importing the name itself.
Positional patterns on plain classes
Using positional sub-patterns on a class that has no __match_args__ raises a TypeError. Plain classes and attribute-only objects need keyword patterns.
Putting it together
Class patterns pay off when you handle a closed set of related types, such as the node types of a small expression tree:
from dataclasses import dataclass
@dataclass
class Num:
value: float
@dataclass
class Add:
left: object
right: object
@dataclass
class Mul:
left: object
right: object
def evaluate(node):
match node:
case Num(value=v):
return v
case Add(left=l, right=r):
return evaluate(l) + evaluate(r)
case Mul(left=Num(value=0)) | Mul(right=Num(value=0)):
return 0
case Mul(left=l, right=r):
return evaluate(l) * evaluate(r)
case _:
raise TypeError(f"unknown node: {node!r}")
tree = Add(Num(2), Mul(Num(3), Num(4)))
print(evaluate(tree)) # 14
print(evaluate(Mul(Num(0), Num(9)))) # 0The Mul case with a zero literal comes before the general Mul case. Reordering them would make the shortcut unreachable. Each case reads as a description of a tree shape, which is the readability gain over a chain of isinstance calls and attribute lookups.
Exercise
Given the dataclass Point(x, y), write a match statement for a variable p that returns "origin" when both coordinates are 0, "on x-axis" when only y is 0, and "other" for any other Point. Why must the origin case come before the x-axis case?
Show answer
match p:
case Point(x=0, y=0): return "origin"
case Point(y=0): return "on x-axis"
case Point(): return "other"
The origin case must come first because Point(y=0) also matches the origin. Cases are tried top to bottom and the first match wins, so the more specific pattern has to be listed before the more general one.
Exercise
What happens when you write case Circle: (no parentheses) as the last case of a match statement, and what happens if it appears before other cases?
Show answer
A bare name is a capture pattern, not a class pattern. As the last case it matches any subject and binds it to the name Circle, which shadows the class. Before other cases, Python raises a SyntaxError because the capture makes the remaining cases unreachable. The fix is case Circle():.