Does this leak?:
static PyObject* foo(PyObject* self, PyObject* args){ PyObject* list = PyList_New(0); for(int i = 0; i < 100; i++) // leak? does PyList_Append increment ref of the temporary? PyList_Append(list, Py_BuildValue("i", 42)); return list; }
Though, I suppose it's better to do this, in any case?:
static PyObject* foo(PyObject* self, PyObject* args){ PyObect* list = PyList_New(100); for(int i = 0; i < 100; i++) PyList_SetItem(list, i, Py_BuildValue("i", 42)); return list; }
PyList_Append
does indeed increment the reference counter, so, yes, the first example will leak. PyList_SetItem
does not, making it a weird exception.
The second option will be slightly more efficient because the list will be allocated to excatly the right size and Python does have to dynamically resize it as items are appended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With