Python pattern matching

Python supports structural pattern matching since version 3.10. Despite this feature being over 4 years old at the time of writing, I rarely see it being used.

Here’s a demonstration of this feature with a simple Point class.

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})'

    def __add__(self, other):
        match other:
            case ( (x, y) | Point(x, y) ):
                return Point(self.x + x, self.y + y)
            case (int(n) | float(n)):
                return Point(self.x + n, self.y + n)
            case n:
                raise TypeError(f'No point addition defined for {type(n)}')

    def __mul__(self, other):
        match other:
            case ( (x, y) | Point(x, y) ):
                return Point(self.x * x, self.y * y)
            case (int(n) | float(n)):
                return Point(self.x * n, self.y * n)
            case n:
                raise TypeError(f'No point multiplication defined for {type(n)}')

    def __getitem__(self, key):
        match key:
            case 0:
                return self.x
            case 1:
                return self.y
            case n:
                raise IndexError(f'Cannot index with key {n}')

    def __setitem__(self, key, value):
        match key:
            case 0:
                self.x = value
            case 1:
                self.y = value
            case n:
                raise IndexError(f'Cannot insert with key {n}')
>>> a = Point(3, 5)
>>> b = Point(2, 2)
>>> c = a * b * (2, 2)

>>> c
Point(12, 20)
>>> c[0], c[1]
(12, 20)
>>> x, y = c
>>> x, y
(12, 20)
>>> c * 10
Point(120, 200)