Sub topic 3
Matching Class Instances with Python `match`
Assume Python 3.10 or later, basic functions and conditionals, and familiarity with classes, dataclasses, and unpacking. A class pattern checks an object's type and selected attributes.
Matching class instances
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
def describe(point):
match point:
case Point(x=0, y=0):
return "origin"
case Point(x, y) if x == y:
return "diagonal"
case Point(x=0) | Point(y=0):
return "axis"
case Point():
return "somewhere else"
case _:
return "not a point"
print(describe(Point(2, 2))) # diagonal
print(describe(Point(0, 5))) # axisPoint(x=0, y=0) matches by keyword. The pattern succeeds only when the subject is a Point with both attributes equal to zero. A guard, such as if x == y, adds a Boolean condition after the pattern matches.
Positional patterns and `__match_args__`
A dataclass normally creates __match_args__ from its fields in declaration order. Therefore, Point(x, y) means the same as Point(x=x, y=y) for this class.
You can define the order yourself:
class User:
__match_args__ = ("name", "admin")
def __init__(self, name, admin):
self.name = name
self.admin = admin
match User("Mina", True):
case User(name, True):
print(f"{name} is an administrator")Keyword patterns are often clearer because they do not depend on field order.
How cases are tried
Python tests cases from top to bottom and stops at the first successful case.
Put specific patterns before general ones. case Point(): matches every Point, so a later case Point(x=0) can never run.
Pitfalls and choosing a construct
A bare name captures a value; it does not compare with a variable:
# case ACTIVE: captures the subject
# case Status.ACTIVE: compares with that enum memberA capture can also make later cases unreachable, producing a syntax error. Avoid changing mutable data inside a guard or while deciding a match. Patterns inspect the subject during matching, so mutation can make behavior surprising.
Use match when you need structural checks, such as an object's type and attributes. Use if/elif for simple Boolean conditions or comparisons where destructuring adds no clarity.
Exercise
Which case should come before case Point()?
Show answer
A more specific case, such as case Point(x=0, y=0), because Point() matches every Point.