I'm writing a Python module in C++.
At a certain point, I need to add a PyObject of an arbitrary type to another one. In other words, do the same as a += b would do in Python. But I haven't been able to find a function in the API that does that.
I tried to do the following,
PyObject* increment(PyObject* a, PyObject* b) {
const auto tp = Py_TYPE(a);
[&]{
if (const auto nb = tp->tp_as_number)
if (auto iadd = nb->nb_inplace_add)
return iadd;
if (const auto sq = tp->tp_as_sequence)
if (auto iadd = sq->sq_inplace_concat)
return iadd;
throw error(PyExc_TypeError,
"type "s+(tp->tp_name)+" does not provide __iadd__");
}()(a,b);
return a;
}
but found out that neither Python float, nor int, nor str implement these methods.
Is there a function in the API that applies a generic +=? If not, how would I write one?
a += 1is the same thing asa = a + 1(well, disassembly showsINPLACE_ADDbut that's not really inplace and__iadd__doesn't exist)__iadd__you could fall back to addition then return the resultoperatormodule has an__iadd__function that should do the right thing. Just call it.PyFloatObjectin C++, e.g.a->ob_fval += 4.2;?