PyListObject & C Modules

Brian Quinlan brian at sweetapp.com
Tue Sep 3 22:43:20 CEST 2002


Martin, are you sure that you don't have a ref counting bug in your
example? Since PyList_GetItem borrows a reference and PyList_SetItem
steels one, you need to do an incref in between. Here is my modified
version (not tested or even compiled):

PyObject*
get_first_elem(PyObject *unused, PyObject *args)
{
  PyObject *list;
  PyObject *first;
  PyObject *result;
  if(!PyArg_ParseTuple("O", &list))
    return NULL;

  if(!PyList_Check(list)) {
    PyErr_SetString(PyExc_TypeError, "get_first_elem expects a list");
    return NULL;
  }

  if(PyList_Size(list) == 0){
    PyErr_SetString(PyExc_ValueError, "empty lists not allowed");
    return NULL;
  }
 
  first = PyList_GetItem(list, 0);
+ if (first == NULL) return NULL;
  result = PyList_New(1);
  if (!result) return NULL;
+ Py_ADDREF(first)
- PyList_SetItem(result, 0, first);
+ if (PyList_SetItem(result, 0, first) != 0) {
+   Py_DECREF(first)
+   Py_DECREF(result);
+   result = NULL;
+ }
  return result;
}

Cheers,
Brian





More information about the Python-list mailing list