matchAdvanced Examples

Begins a structural pattern matching block (3.10+)

Class patterns

Matching against class instances.

python
class Point:
    __match_args__ = ("x", "y")
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return f"Point({self.x}, {self.y})"

class Circle:
    __match_args__ = ("center", "radius")
    def __init__(self, center, radius):
        self.center = center
        self.radius = radius

def describe(shape):
    match shape:
        case Circle(center=Point(0, 0), radius=r):
            return f"Circle at origin, r={r}"
        case Circle(center=Point(x, y), radius=r) if r > 10:
            return f"Large circle at ({x},{y}), r={r}"
        case Circle(Point(x, y) as center, r):
            return f"Circle at {center}, r={r}"
        case Point(0, 0):
            return "Origin"
        case Point(x, y):
            return f"Point({x}, {y})"

shapes = [
    Point(0, 0), Point(3, 4),
    Circle(Point(0, 0), 5),
    Circle(Point(1, 2), 15),
]
for s in shapes:
    print(f"  {describe(s)}")

__match_args__ defines positional pattern matching for classes. Class patterns let you destructure object attributes and combine with guards for powerful matching.

Want to try these examples interactively?

Open Advanced Playground