Phase 15 of 25 · Topic 15.3

Class Pattern Matching & __match_args__

1Concept

Class pattern matching inspects instance types and extracts attributes. Defining `__match_args__ = ('x', 'y')` allows positional arguments in case statements (`case Point(x, y):`).

2Architecture Diagram

class Point: __match_args__ = ('x', 'y')
match p:
  case Point(0, 0):  ---> Origin
  case Point(x, y):  ---> Binds x and y

3Code Example

Python 3.12
class GeoLocation:
    __match_args__ = ("lat", "lon")
    def __init__(self, lat: float, lon: float):
        self.lat, self.lon = lat, lon

def route_request(location):
    match location:
        case GeoLocation(0.0, 0.0):
            return "Null Island Coordinate"
        case GeoLocation(lat, lon) if lat > 0:
            return f"Northern Hemisphere: ({lat}, {lon})"
        case GeoLocation(lat, lon):
            return f"Southern Hemisphere: ({lat}, {lon})"
        case _:
            return "Invalid Location"

print(route_request(GeoLocation(37.77, -122.41)))
print(route_request(GeoLocation(0.0, 0.0)))

4Expected Output

Northern Hemisphere: (37.77, -122.41)
Null Island Coordinate

5Key Takeaways

  • Dataclasses and NamedTuples automatically generate `__match_args__`.
  • `isinstance()` check is performed implicitly by class patterns.
  • Positional arguments in case patterns match against attributes in `__match_args__` order.