G
Giacomo Alzetta
I'm trying to implement a c-extension which defines a new class(ModPolynomial on the python side, ModPoly on the C-side).
At the moment I'm writing the in-place addition, but I get a *really* strange behaviour.
Here's the code for the in-place addition:
#define ModPoly_Check(v) (PyObject_TypeCheck(v, &ModPolyType))
[...]
static PyObject *
ModPoly_InPlaceAdd(PyObject *self, PyObject *other)
{
if (!ModPoly_Check(self)) {
// This should never occur for in-place addition, am I correct?
if (!ModPoly_Check(other)) {
PyErr_SetString(PyExc_TypeError, "Neither argument is a ModPolynomial.");
return NULL;
}
return ModPoly_InPlaceAdd(other, self);
} else {
if (!PyInt_Check(other) && !PyLong_Check(other)) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
}
ModPoly *Tself = (ModPoly *)self;
PyObject *tmp, *tmp2;
tmp = PyNumber_Add(Tself->ob_item[0], other);
tmp2 = PyNumber_Remainder(tmp, Tself->n_modulus);
Py_DECREF(tmp);
tmp = Tself->ob_item[0];
Tself->ob_item[0] = tmp2;
Py_DECREF(tmp);
printf("%d\n", (int)ModPoly_Check(self));
return self;
}
And here's an example usage:
Now, how come my ModPolynomial suddenly becomes a read-only buffer, even though that last printf tells us that the object returned is of the correct type?
If I raise an exception instead of returning self, the ModPolynomial gets incremented correctly. If I use the Py_RETURN_NONE macro, the ModPolynomial is correctly replaced by None.
At the moment I'm writing the in-place addition, but I get a *really* strange behaviour.
Here's the code for the in-place addition:
#define ModPoly_Check(v) (PyObject_TypeCheck(v, &ModPolyType))
[...]
static PyObject *
ModPoly_InPlaceAdd(PyObject *self, PyObject *other)
{
if (!ModPoly_Check(self)) {
// This should never occur for in-place addition, am I correct?
if (!ModPoly_Check(other)) {
PyErr_SetString(PyExc_TypeError, "Neither argument is a ModPolynomial.");
return NULL;
}
return ModPoly_InPlaceAdd(other, self);
} else {
if (!PyInt_Check(other) && !PyLong_Check(other)) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
}
ModPoly *Tself = (ModPoly *)self;
PyObject *tmp, *tmp2;
tmp = PyNumber_Add(Tself->ob_item[0], other);
tmp2 = PyNumber_Remainder(tmp, Tself->n_modulus);
Py_DECREF(tmp);
tmp = Tself->ob_item[0];
Tself->ob_item[0] = tmp2;
Py_DECREF(tmp);
printf("%d\n", (int)ModPoly_Check(self));
return self;
}
And here's an example usage:
Now, how come my ModPolynomial suddenly becomes a read-only buffer, even though that last printf tells us that the object returned is of the correct type?
If I raise an exception instead of returning self, the ModPolynomial gets incremented correctly. If I use the Py_RETURN_NONE macro, the ModPolynomial is correctly replaced by None.