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?