overloading arbitrary operator in python

Viewed 207

Is it possible to overload arbitrary operators in Python? Or is one restricted to the list of operators which have associated magic methods as listed here: https://www.python-course.eu/python3_magic_methods.php ?

I'm asking because I noticed that Numpy uses the @ operator to perform matrix multiplication e.g. C=A@B where A,B are Numpy arrays, and I was wondering how they did it.

Edit: The @ operator is not in the list I linked to.

Could someone point me to the Numpy source where this is done?

1 Answers

In Python, you cannot create new operators, no. By defining those "magic" functions, you can affect what happens when objects of your own definition are operated upon using the standard operators.

However, the list you linked to is not complete. In Python 3.5, they added special methods for the @ operator. Here's the rather terse listing in the Python operator module docs and here are the docs on operator overloading.

operator.matmul(a, b)

operator.__matmul__(a, b)

Return a @ b.

New in version 3.5.

I hadn't seen that operator personally, so I did a little more research. It's intended specifically for matrix multiplication. But, I was able to use it for other purposes, though I would argue against doing so as a matter of style:

In [1]: class RichGuyEmailAddress(str): 
   ...:     def __matmul__(self, domain_name): 
   ...:         return f'{self}@{domain_name}' 
   ...:                                                                                                                                                                                       

In [2]: my_email = RichGuyEmailAddress('billg') @ 'microsoft.com'                                                                                                                              

In [3]: print(my_email)                                                                                                                                                                       
billg@microsoft.com

So, no, you can't overload any random character, but you can overload the @ operator.

Related