开发者

Does this PyList_Append(list, Py_BuildValue(...)) leak?

开发者 https://www.devze.com 2023-01-11 21:35 出处:网络
Does this leak?: static PyObject* foo(PyObject* self, PyObject* args){ PyObject* list = PyList_New(0); for(int i = 0; i < 100; i++)

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++开发者_Go百科)
        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.

0

精彩评论

暂无评论...
验证码 换一张
取 消