error-handlingpython-c-api

How to dispose off a partially initialized list in Python C-API?


The documentation for PyList_New says that these two APIs are safe before the list is fully initialized: PyList_SetItem() and PyList_SET_ITEM(). But if an error happens in the middle of initializing the list, what should I do?

    PyObject* my_list = PyList_New(count);
    if (!my_list) {
        return PyErr_NoMemory();
    }
    for (int i = 0; i < count; i++) {
        PyObject* element = _function_may_set_exc_and_return_null();
        if (!element) {
            // what to do here??
            return NULL;
        }
        PyList_SET_ITEM(my_list, i, element);
    }
    return my_list;

Solution

  • You Py_DECREF it.

    The list items are themselves decrefed with Py_XDECREF to account for the possibility that they might be NULL. See https://github.com/python/cpython/blob/bb594e801b6a84823badbb85b88f0fc8b221d7bf/Objects/listobject.c#L509 for the current implementation.