Search code examples
pythoncpython

Writing a Python C type, and want to write a multiplication operator


I'm writing a special numerical type for Python in C as an extension, and I want to provide it with a specialized binary multiplication operator.

static PyMethodDef pyquat_Quat_methods[] = {
  {"__mul__", (PyCFunction)pyquat_Quat_mul, METH_O, "multiply unit quaternion by another using the Hamiltonian definition"},
  {NULL, NULL, 0, NULL}  /* Sentinel */
};

If I then compile and load the library, I can successfully create instances of the object called x and y. I can even do

w = x.__mul__(y)

But if I try to do

w = x * y

I get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'pyquat.Quat' and 'pyquat.Quat'

Is there some way I need to tell Python to treat __mul__ as the binary multiplication operator?


Solution

  • If you want a type written in C to support multiplication, you need to provide a tp_as_number field with an nb_multiply function for multiplication, and you need to not explicitly provide a __mul__ method. __mul__ will be handled for you. It may help to look at how built-in types do it.