ZetCode

Python __matmul__ Method

Last modified November 18, 2026 Python 3.15

The @ operator calls __matmul__ on its left operand. It was introduced to give matrix multiplication its own syntax, distinct from the element-wise *. This article builds a small pure-Python matrix type, checks dimensions, computes dot products and rotations, and shows how @= and operator.matmul use the same protocol.

Basic matrix multiplication

The hook receives the right operand, verifies that the shapes are compatible, and returns a new matrix. The loops compute each entry as the dot product of a row from the left matrix and a column from the right one.

basic_matmul.py
class Matrix:
    def __init__(self, rows):
        self.rows = [list(row) for row in rows]

    def __matmul__(self, other):
        if not isinstance(other, Matrix):
            return NotImplemented
        if len(self.rows[0]) != len(other.rows):
            raise ValueError("incompatible dimensions")
        return Matrix([
            [sum(a * b for a, b in zip(row, col))
             for col in zip(*other.rows)]
            for row in self.rows
        ])

    def __repr__(self):
        return f"Matrix({self.rows})"


a = Matrix([[1, 2], [3, 4]])
b = Matrix([[5, 6], [7, 8]])
print(a @ b)

The entry in row 0, column 0 is 1*5 + 2*7 = 19; the other entries follow the same rule. Returning NotImplemented for an unrelated type lets Python try the reflected operation or raise TypeError.

$ python basic_matmul.py
Matrix([[19, 22], [43, 50]])

Dimension checks

Matrix products are defined only when the number of columns in the left matrix equals the number of rows in the right one. Checking this up front gives a clear error instead of a silently wrong result.

dims_matmul.py
class Matrix:
    def __init__(self, rows):
        self.rows = [list(row) for row in rows]

    def __matmul__(self, other):
        if len(self.rows[0]) != len(other.rows):
            raise ValueError("incompatible dimensions")
        return "product"


a = Matrix([[1, 2, 3], [4, 5, 6]])
b = Matrix([[7], [9], [11]])
print(a @ b)
try:
    print(b @ a)
except ValueError as e:
    print(type(e).__name__, e)

The first product is valid because a has three columns and b has three rows. Reversing the operands would require b's single column to match a's two rows, so the hook rejects it.

$ python dims_matmul.py
product
ValueError incompatible dimensions

Vector dot products

The operator is not limited to matrices. A vector class can use @ for the dot product, which is the same sum-of-products used for a single matrix entry.

vector_dot.py
class Vector:
    def __init__(self, *components):
        self.components = list(components)

    def __matmul__(self, other):
        if not isinstance(other, Vector):
            return NotImplemented
        if len(self.components) != len(other.components):
            raise ValueError("vectors must have the same length")
        return sum(a * b for a, b in zip(self.components,
                                        other.components))

    def __repr__(self):
        return f"Vector({self.components})"


v1 = Vector(1, 2, 3)
v2 = Vector(4, 5, 6)
print(v1 @ v2)
try:
    Vector(1, 2) @ v2
except ValueError as e:
    print(type(e).__name__, e)

The dot product is 1*4 + 2*5 + 3*6 = 32, a plain integer rather than a vector. Vectors of different lengths are rejected before any multiplication happens.

$ python vector_dot.py
32
ValueError vectors must have the same length

Chained products and associativity

The @ operator is left-associative, so a @ b @ c evaluates a @ b first and applies @ c to the result. Matrix multiplication is associative, so regrouping gives the same answer.

chained_matmul.py
class Matrix:
    def __init__(self, rows):
        self.rows = [list(row) for row in rows]

    def __matmul__(self, other):
        return Matrix([
            [sum(a * b for a, b in zip(row, col))
             for col in zip(*other.rows)]
            for row in self.rows
        ])

    def __eq__(self, other):
        return isinstance(other, Matrix) and self.rows == other.rows

    def __repr__(self):
        return f"Matrix({self.rows})"


a = Matrix([[1, 2], [3, 4]])
b = Matrix([[5, 6], [7, 8]])
c = Matrix([[1, 0], [0, 1]])
print((a @ b) @ c)
print(a @ (b @ c))
print((a @ b) @ c == a @ (b @ c))

Both groupings print the same matrix and compare equal once __eq__ is defined. Without it, two matrices with identical rows would compare unequal because the default identity-based comparison would be used.

$ python chained_matmul.py
Matrix([[19, 22], [43, 50]])
Matrix([[19, 22], [43, 50]])
True

A rotation transform

A transformation matrix can be applied to a point with @. Using the standard math module keeps the example self-contained; the results are rounded only for display.

rotation.py
import math


class Transform:
    def __init__(self, matrix):
        self.matrix = [list(row) for row in matrix]

    def __matmul__(self, vector):
        if len(self.matrix[0]) != len(vector):
            raise ValueError("incompatible dimensions")
        return [sum(m * v for m, v in zip(row, vector))
                for row in self.matrix]

    def __repr__(self):
        return f"Transform({self.matrix})"


theta = math.radians(45)
rotation = Transform([[math.cos(theta), -math.sin(theta)],
                      [math.sin(theta), math.cos(theta)]])
print([round(x, 4) for x in rotation @ [1, 0]])
print([round(x, 4) for x in rotation @ [0, 1]])

Rotating the point (1, 0) by 45 degrees gives approximately (0.7071, 0.7071), and (0, 1) becomes (-0.7071, 0.7071). These are the expected coordinates for a quarter-diagonal rotation.

$ python rotation.py
[0.7071, 0.7071]
[-0.7071, 0.7071]

In-place matrix multiplication

The @= operator calls __imatmul__ when it exists. A mutable matrix can update its rows and return self so aliases see the change.

imatmul.py
class Matrix:
    def __init__(self, rows):
        self.rows = [list(row) for row in rows]

    def __matmul__(self, other):
        if not isinstance(other, Matrix):
            return NotImplemented
        return Matrix([
            [sum(a * b for a, b in zip(row, col))
             for col in zip(*other.rows)]
            for row in self.rows
        ])

    def __imatmul__(self, other):
        print("__imatmul__")
        product = self @ other
        self.rows = product.rows
        return self

    def __repr__(self):
        return f"Matrix({self.rows})"


m = Matrix([[1, 0], [0, 1]])
alias = m
m @= Matrix([[1, 1], [1, 0]])
print(m, alias, m is alias)

Multiplying the identity matrix by the second matrix leaves the second matrix as the result. The True at the end confirms that the object was updated rather than replaced.

$ python imatmul.py
__imatmul__
Matrix([[1, 1], [1, 0]]) Matrix([[1, 1], [1, 0]]) True

The operator.matmul function

operator.matmul(a, b) is the functional form of a @ b. It calls the same hook and is convenient when a callable is needed.

operator_matmul.py
import operator


class Matrix:
    def __init__(self, rows):
        self.rows = [list(row) for row in rows]

    def __matmul__(self, other):
        return Matrix([
            [sum(a * b for a, b in zip(row, col))
             for col in zip(*other.rows)]
            for row in self.rows
        ])

    def __repr__(self):
        return f"Matrix({self.rows})"


a = Matrix([[1, 2]])
b = Matrix([[3], [4]])
print(operator.matmul(a, b))

A one-by-two matrix multiplied by a two-by-one matrix yields a one-by-one result: 1*3 + 2*4 = 11. The functional form gives the same answer as a @ b.

$ python operator_matmul.py
Matrix([[11]])

Best practices

A few rules keep @ predictable:

Source

object.__matmul__ - Python documentation

Binary arithmetic operations - Python documentation

operator.matmul - Python documentation

PEP 465 - A dedicated infix operator for matrix multiplication

In this article we have implemented the __matmul__ method. We have covered basic products, dimension checks, dot products, chained operations, rotations, @= and operator.matmul using only pure Python. For related topics, see Python __mul__ method, Python __imatmul__ method, and Python NumPy matmul().

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.