## Syntax

object.__matmul__(self, other)

The Python `__matmul__()`

method is called to implement the matrix multiplication operation `@`

. For example to evaluate the expression `x @ y`

, Python attempts to call `x.__matmul__(y)`

.

We call this a *“Dunder Method”* for *“ Double Underscore Method”* (also called

*“magic method”*). To get a list of all dunder methods with explanation, check out our dunder cheat sheet article on this blog.

The `@`

operator was introduced to Python’s core syntax from 3.5 onwards thanks to PEP 465. Its only goal is to solve the problem of matrix multiplication. It even comes with a nice mnemonic – `@`

is * for m**AT**rices.

It is unusual that `@`

was added to the core Python language when it’s only used with certain libraries. Fortunately, the only other time we use `@`

is for decorator functions. So you are unlikely to get confused.

## Example

In the following example, you create a custom class `Data`

and overwrite the `__matmul__()`

method that simply returns a dummy string. The real computation could be much more sophisticated, of course.

class Data: def __matmul__(self, other): return '... my result of matmul...' a = Data() b = Data() c = a @ b print(c) # ... my result of matmul...

If you hadn’t defined the `__matmul__()`

method, Python would’ve raised a `TypeError`

.

## How to Resolve TypeError: unsupported operand type(s) for @

Consider the following code snippet where you try to multiply two custom objects without defining the dunder method `__matmul__()`

:

class Data: pass a = Data() b = Data() c = a @ b print(c)

Running this leads to the following error message on my computer:

Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 7, in <module> c = a @ b TypeError: unsupported operand type(s) for @: 'Data' and 'Data'

The reason for this error is that the `__matmul__()`

dunder method has never been defined—and it is not defined for a custom object by default. So, to resolve the `TypeError: unsupported operand type(s) for @`

, you need to provide the `__matmul__(self, other)`

method in your class definition as shown previously:

class Data: def __matmul__(self, other): return '... my result of matmul...'

## NumPy Matrix Multiplication @

To perform matrix multiplication between two NumPy arrays, check out the `@`

operator:

# Python >= 3.5 # 2x2 arrays where each value is 1.0 >>> A = np.ones((2, 2)) >>> B = np.ones((2, 2)) >>> A @ B array([[2., 2.], [2., 2.]])

I’ll give you a more detailed introduction in the following video or this blog tutorial.

## Python __matmul__ vs __rmatmul__

Say, you want to matrix-multiply two objects `x`

and `y`

.

print(x @ y)

Python first tries to call the left object’s `__matmul__()`

method `x.__matmul__(y)`

. But this may fail for two reasons:

- The method
`x.__matmul__()`

is not implemented in the first place, or - The method
`x.__matmul__()`

is implemented but returns a`NotImplemented`

value indicating that the data types are incompatible.

If this fails, Python tries to fix it by calling the `y.__rmatmul__()`

for *reverse matrix multiplication* on the right operator `y`

. If this method is implemented, Python knows that it doesn’t run into a potential problem of a non-commutative operation. If it would just execute `y.__matmul__(x)`

instead of `x.__matmul__(y)`

, it could cause an error if the multiplication is non-commutative. That’s why `y.__rmatmul__(x)`

is needed which indicates that matrix multiplication is possible after all.

So, the difference between `x.__matmul__(y)`

and `x.__rmatmul__(y)`

is that the former calculates `x @ y`

whereas the latter calculates `y @ x`

— both calling the respective matrix multiplication method defined on object `x`

.

**References:**

## Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

**You build high-value coding skills by working on practical coding projects!**

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is ** YES!**, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.