Search code examples
pythoncpython-modulepython-c-apicpython

Python C module function argument reference counting


When I have a PyObject * obtained from PyArg_ParseTuple, do I need to make sure to Py_DECREF it before I return from the function?

Example:

static PyObject * modulefunc(PyObject * self, PyObject * args) {
    PyObject * obj;
    if (!PyArg_ParseTuple(args, "O", &obj)) {
        return NULL;
    }

    if (!PyObject_TypeCheck(obj, expected_type_ptr)) {
        // Do I need to Py_DECREF(obj) here?
        PyErr_SetString(PyExc_TypeError, "First argument is not expected type.");
        return NULL;
    }

    // ... rest of function implementation.
}

Solution

  • No. PyArg_ParseTuple gives you a borrowed reference.