Sub topic 10
Matching class instances
This chapter assumes you know Python 3.10 or later, dataclasses, and the literal, capture, wildcard, or-pattern, and guard syntax from earlier chapters.
What a class pattern does
A class pattern looks like a constructor call, but it does not create an object. It tests an existing one. Point(x=0, y=0) asks two questions in order:
- Is the subject an instance of
Point? Subclasses count, because Python usesisinstance. - Does each listed attribute match its sub-pattern?
The sub-patterns inside the parentheses can be any pattern you already know: literals, captures, wildcards, or-patterns, or more class patterns.
A worked example
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) if x == y:
return "on the diagonal"
case Point(x=0) | Point(y=0):
return "on an axis"
case Point():
return "elsewhere"
case _:
return "not a point"
print(where(Point(2, 2))) # on the diagonal
print(where(Point(0, 5))) # on an axis
print(where(Point(1, 2))) # elsewhere
print(where("hello")) # not a pointEach case does something different:
Point(x=0, y=0)uses keyword patterns. Python readsp.xandp.yand compares them with the literal0.Point(x, y)uses positional patterns. The namesxandyare captures, so they bind the attribute values. The guardif x == ythen filters the result.Point(x=0) | Point(y=0)combines two class patterns with|. You only need to list the attributes you care about.Point()checks the type and nothing else. It is the usual way to say "anyPoint".
Keyword versus positional patterns
Keyword patterns work with any object. Python simply reads the named attribute with getattr. If the attribute does not exist, the case fails quietly. It does not raise AttributeError.
Positional patterns need to know which attribute each position refers to. That information comes from the class attribute __match_args__. The @dataclass decorator sets it to ("x", "y") for you. A plain class has no __match_args__, so Point(x, y) would raise a TypeError. The next chapter covers how to define it yourself.
A few built-in types accept a single positional pattern that matches the whole value. This lets you test a type and capture in one step:
def describe(value):
match value:
case int(n) if n < 0:
return f"negative int {n}"
case int(n):
return f"int {n}"
case str(s):
return f"string of length {len(s)}"
case list() | tuple():
return "a sequence"
case _:
return "something else"
print(describe(-4)) # negative int -4
print(describe("abc")) # string of length 3
print(describe((1, 2))) # a sequencebool is a subclass of int, so describe(True) takes the int(n) branch.
Common errors
- Forgetting the parentheses.
case Point:is a capture pattern, not a type check. It matches everything and binds the namePoint. Python rejects it with aSyntaxErrorif later cases follow, because they could never run. - Positional patterns on a plain class. Without
__match_args__you get aTypeError. Use keyword patterns instead. - Expecting an error on a missing attribute. A missing attribute means no match, so a typo such as
Point(z=0)never matches and gives you no warning. - Putting a general case first.
Point()placed abovePoint(x=0, y=0)hides the specific case.
Exercise
Given @dataclass class Circle: r: float and @dataclass class Rect: w: float; h: float, write a function area(shape) using match that returns the area of a Circle (use 3.14 for pi) or a Rect. It should raise ValueError for anything else, and return 0 for a Rect with a zero side.
Show answer
def area(shape): match shape: case Rect(w=0) | Rect(h=0): return 0 case Circle(r): return 3.14 r r case Rect(w, h): return w * h case _: raise ValueError("unknown shape")