Python __imatmul__ Method
Last modified November 18, 2026 Python 3.15
The @= operator calls __imatmul__ on its left
operand. It is the in-place form of the matrix multiplication operator
introduced in Python 3.5. A mutable object should update itself and return
self; otherwise Python falls back to __matmul__.
This article builds the hook from first principles in plain Python.
The @= dispatch
a @= b is evaluated as
a = type(a).__imatmul__(a, b). The method gets both operands,
performs the multiplication, and returns the object to be bound back to the
name. The example also keeps a second reference to show that the object was
changed rather than replaced.
class Matrix:
def __init__(self, rows):
self.rows = [list(row) for row in rows]
def __imatmul__(self, other):
print("__imatmul__")
if len(self.rows[0]) != len(other.rows):
raise ValueError("incompatible dimensions")
self.rows = [
[sum(a * b for a, b in zip(row, col))
for col in zip(*other.rows)]
for row in self.rows
]
return self
def __repr__(self):
return f"Matrix({self.rows})"
a = Matrix([[1, 2], [3, 4]])
alias = a
b = Matrix([[5, 6], [7, 8]])
a @= b
print(a)
print(a is alias, alias)
The product of the two matrices is [[19, 22], [43, 50]].
Because the hook returned self, alias still points
at the same object and shows the new rows. The dimension check uses the
number of columns of the left operand and the number of rows of the right
one.
$ python basic_imatmul.py __imatmul__ Matrix([[19, 22], [43, 50]]) True Matrix([[19, 22], [43, 50]])
Fallback to __matmul__
With no __imatmul__, Python evaluates
a @= b as a = a @ b. The regular
__matmul__ hook builds a new object, which is then assigned back
to the name.
class Matrix:
def __init__(self, rows):
self.rows = [list(row) for row in rows]
def __matmul__(self, other):
print("__matmul__")
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})"
m = Matrix([[1, 2], [3, 4]])
alias = m
m @= Matrix([[5, 6], [7, 8]])
print(m, alias, m is alias)
The trace shows __matmul__ being called instead. The alias
keeps the original rows and the identity test is False. For a
large matrix this fallback also allocates a second matrix, which is why
libraries implement the in-place hook.
$ python fallback_matmul.py __matmul__ Matrix([[19, 22], [43, 50]]) Matrix([[1, 2], [3, 4]]) False
Validating dimensions
Matrix multiplication is only defined when the inner dimensions agree.
Failing early with ValueError gives a clearer message than an
index error deep inside the loop.
class Matrix:
def __init__(self, rows):
self.rows = [list(row) for row in rows]
def __imatmul__(self, other):
print("__imatmul__")
if len(self.rows[0]) != len(other.rows):
raise ValueError("incompatible dimensions")
self.rows = [
[sum(a * b for a, b in zip(row, col))
for col in zip(*other.rows)]
for row in self.rows
]
return self
def __repr__(self):
return f"Matrix({self.rows})"
a = Matrix([[1, 2], [3, 4]])
try:
a @= Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
except ValueError as e:
print(type(e).__name__, e)
print(a)
The left matrix has two columns while the right one has three rows, so
the hook raises before assigning to self.rows. The final line
confirms the original matrix is unchanged after the failed operation.
$ python dimension_check.py __imatmul__ ValueError incompatible dimensions Matrix([[1, 2], [3, 4]])
The operator.imatmul function
The operator module provides the functional form
operator.imatmul(a, b). It calls the hook but does not rebind a
variable in the caller's scope.
import operator
class Matrix:
def __init__(self, rows):
self.rows = [list(row) for row in rows]
def __imatmul__(self, other):
self.rows = [
[sum(a * b for a, b in zip(row, col))
for col in zip(*other.rows)]
for row in self.rows
]
return self
def __repr__(self):
return f"Matrix({self.rows})"
x = Matrix([[1, 2], [3, 4]])
y = Matrix([[5, 6], [7, 8]])
res = operator.imatmul(x, y)
print(x, res, x is res)
try:
operator.imatmul([1, 2], [3, 4])
except TypeError as e:
print(type(e).__name__, e)
The mutable Matrix returns the object it changed, so both
x and res refer to it. Plain lists have no
__imatmul__, so the function raises TypeError.
$ python operator_imatmul.py Matrix([[19, 22], [43, 50]]) Matrix([[19, 22], [43, 50]]) True TypeError unsupported operand type(s) for @=: 'list' and 'list'
NotImplemented and the reflected method
When the right operand is not a supported matrix, return
NotImplemented. Python then tries __matmul__ on the
left and __rmatmul__ on the right operand.
class Right:
def __rmatmul__(self, other):
print("__rmatmul__")
return "handled"
class Matrix:
def __init__(self, rows):
self.rows = [list(row) for row in rows]
def __imatmul__(self, other):
if not isinstance(other, Matrix):
return NotImplemented
self.rows = [
[sum(a * b for a, b in zip(row, col))
for col in zip(*other.rows)]
for row in self.rows
]
return self
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 __repr__(self):
return f"Matrix({self.rows})"
m = Matrix([[1, 2], [3, 4]])
m @= Right()
print(m)
Both hooks on Matrix decline the Right object, so
its __rmatmul__ runs. Its return value, the string
"handled", is bound to m. Returning
NotImplementedError here would be wrong: that is an exception,
not a signal to try the reflected operation.
$ python reflected_imatmul.py __rmatmul__ handled
Repeated multiplication in place
A matrix power is a natural use for @=. Starting from the
identity matrix and applying the same transition repeatedly avoids creating
a fresh matrix on every step.
class Matrix:
def __init__(self, rows):
self.rows = [list(row) for row in rows]
def __imatmul__(self, other):
self.rows = [
[sum(a * b for a, b in zip(row, col))
for col in zip(*other.rows)]
for row in self.rows
]
return self
def __repr__(self):
return f"Matrix({self.rows})"
base = Matrix([[1, 1], [1, 0]])
p = Matrix([[1, 0], [0, 1]])
for _ in range(5):
p @= base
print(p)
The fifth power of the Fibonacci transition matrix is
[[8, 5], [5, 3]]. Only one object is updated in the loop;
without the in-place hook each step would allocate a new matrix.
$ python matrix_powers.py Matrix([[8, 5], [5, 3]])
Best practices
A few rules keep matrix-style in-place operators predictable:
- Return
selfafter changing a mutable object; the operator binds the return value. - Implement
__matmul__as well so@and@=both work. - Validate inner dimensions before writing any rows.
- Return
NotImplementedfor unsupported operands to allow reflected operations. - Keep the object’s type consistent instead of returning a plain list or tuple from the hook.
Source
object.__imatmul__ - Python documentation
Emulating numeric types - Python documentation
operator.imatmul - Python documentation
PEP 465 - A dedicated infix operator for matrix multiplication
In this article we have implemented the __imatmul__ method.
We have covered the @= dispatch, the fallback to
__matmul__, dimension checks, reflected operations, and a matrix
power loop. For related topics, see
Python __matmul__ method,
Python __imul__ method, and
Python matrices.
Author
List all Python tutorials.