递增 Py_True/Py_False refcount 总是必要的吗?

Is incrementing Py_True/Py_False refcount always necessary?

我是 Python C-API 的新手,正在浏览一些源代码以挑选其中的一部分。

这是我在包含扩展模块的包的 C 源代码中找到的函数的最小版本:

#define PY_SSIZE_T_CLEAN
#include <Python.h>

static PyObject *
modulename_myfunc(PyObject *self, PyObject *args) {

    // Call PyArg_ParseTuple, etc ...

    // Dummy values; in the real function they are calculated
    int is_found = 1;
    Py_ssize_t n_bytes_found = 1024;

    PyObject *result;
    result = Py_BuildValue("(Oi)",
                           is_found ? Py_True : Py_False,  // Py_INCREF?
                           n_bytes_found);
    return result;
}

这是否会因未能在 Py_TruePy_False 上使用 Py_INCREF 而引入小的内存泄漏? C-API docs for Boolean object 似乎很明确总是需要 incref/decref Py_TruePy_False.

如果确实需要引入 Py_INCREF,假设 Py_RETURN_TRUE/Py_RETURN_FALSE 不是真正适用的,如何最恰当地在这里使用它,因为正在使用元组回来了吗?

此处未使用 Py_INCREF 的原因是因为 Py_BuildValue,当传递带有 "O" 的对象时将为您增加引用计数:

O (object) [PyObject *]

Pass a Python object untouched (except for its reference count, which is incremented by one). If the object passed in is a NULL pointer, it is assumed that this was caused because the call producing the argument found an error and set an exception. Therefore, Py_BuildValue() will return NULL but won’t raise an exception. If no exception has been raised yet, SystemError is set.

例如,您将在 CPython itself 中看到类似的用法。