I am writing a new type of extension, but I have a problem setting numerical operations (e.g. addition / subtraction / multiplication). I managed to set some operations in place, while normal operations are not called.
For example, I have a function:
static PyObject * MyType_Mul(PyObject *v, PyObject *w) { PyErr_SetString(PyExc_ValueError, "testing"); return NULL; }
And I asked it in number methods like this:
static PyNumberMethods my_type_as_number = { 0, 0, (binaryfunc)MyType_Mul, ... 0, 0, (binaryfunc)MyType_Mul, ... };
Now, when I try to use my type, I get this behavior:
>>> from mytype import MyType >>> a = MyType() >>> a * 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for *: 'mytype.MyType' and 'int' >>> 2 * a Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for *: 'int' and 'mytype.MyType'
But if I use the in-place operator:
>>> a *= 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: testing
If I use dir() for an object, I can see the __mul__ and __rmul__ (which means that python sees them), but it looks like they are not being called at all. Using a.__mul__(2) returns NotImplemented .
also:
>>> a.__mul__ <method-wrapper '__mul__' of mytype.MyType object at 0x7fc2ecc50468> >>> a.__imul__ <method-wrapper '__imul__' of mytype.MyType object at 0x7fc2ecc50468>
so, as you can see, this is exactly the same thing.
What's happening? Why does the same exact function work for the operator in place, but not for the "normal" operator? I also thought that I could use the wrong slot, but I checked twice, and it is correct, as well as setting it to nb_add , nb_sub , etc. Does not work.