Skip to main content

How to Use the @ Matrix Multiplication Operator in Python

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Python has an operator just for matrix multiplication: @. Python itself never uses it, so it does nothing until a class defines what it means. This guide makes @ work on a small class of two-number vectors on Python 3.15.2.

Syntax​

Syntax
<a> @ <b>
PartWhat it means
<a>, <b>Two values whose class supports @
@Python calls the __matmul__ method of <a>'s class with <b>, and uses what it returns

The Python reference says: "The @ (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this operator." It adds that the operation "can be customized using the special matmul() and rmatmul() methods."

The Example​

A Vector class holds two numbers, x and y, and defines @ as the dot product: the x values multiplied, plus the y values multiplied.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

matmul_operator.py
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y

def __matmul__(self, other):
return self.x * other.x + self.y * other.y


a = Vector(1, 2)
b = Vector(3, 4)
print(a @ b)

The matmul_operator.py script in a macOS-style code window: a Vector class whose matmul method returns self.x * other.x + self.y * other.y, then a @ b for Vector(1, 2) and Vector(3, 4).

__init__ stores the two numbers. __matmul__ is the method @ calls: self is the vector on the left of @, and other the one on the right.

Step 2: Run It​

Terminal
uv run python matmul_operator.py
Output
11

The terminal after uv run python matmul_operator.py: 11.

a @ b called a.__matmul__(b), which returned 1 × 3 + 2 × 4 = 11. The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
@ on two lists[1, 2] @ [3, 4] stopped with TypeError: unsupported operand type(s) for @: 'list' and 'list'Use a class that defines __matmul__, or a library whose types support @
Defining __matmul__ without return@ printed None: the method worked out the number and dropped itReturn the result

FAQ​

Is this the same @ as in decorators?​

No. An @ at the start of a line, just above a def or class, is a decorator: the reference says "A function definition may be wrapped by one or more decorator expressions." The operator sits between two values.

Which values can be on each side?​

Whatever the method accepts. Python calls __matmul__ of the left value's class with the right value, so the left class decides.

Conclusion​

Vector(1, 2) @ Vector(3, 4) printed 11, because the class's __matmul__ defined @ as the dot product. Two plain lists stopped with a TypeError: no built-in type supports @.

Additional Resources​