I am lost on Py_DECREF/INCREF when handling PyList_Append. Can anybody have comments on the following codes?
PyObject * bugmaybe(PyObject *self, PyObject *args)
{
PyObject * trio=PyList_New(0);
PyObject * trio_tmp;
PyObject * otmp = PyFloat_FromDouble(1.2);
PyList_Append(trio_tmp,otmp);
//Py_DECREF(otmp);
otmp = PyFloat_FromDouble(2.3);
PyList_Append(trio_tmp,otmp);
//Py_DECREF(otmp);
PyList_Append(trio,trio_tmp);
Py_INCREF(trio_tmp);
}
If you know the size of the list upfront its usually faster to create the list with the right size and use
PyList_SetItem()
.Your code is simply wrong,
trio_tmp
is uninitialized.Try this:
If you really want to use
PyList_Append
, your code was mostly ok, just missing the initialization fortrio_tmp
and the superfluous Py_INCREF at the end.The code above would be equivalent to:
Hope it helps. The main hint is in the docs, if it says 'Steals a reference' then the function basically takes ownership, if it says 'New Reference' then it did an INCREF for you, if nothing is said it probably does an INCREF and DECREF pair as needed.