There are some Python C-API functions that steal a reference for one passed argument for example PyList_SetItem
, while others increment the reference counts of the argument, for example PyList_Append
.
Can I tell Cython that the reference will be stolen? Or do I need to use Py_INCREF
manually?
from cpython.object cimport PyObject
from cpython.ref cimport Py_INCREF
cdef extern from "Python.h":
void PyList_SetItem(object list, Py_ssize_t i, object o)
cpdef void func(list lst, object item):
Py_INCREF(item)
PyList_SetItem(lst, 0, item)
I know that if a function returns a borrowed references one can change the return type (PyObject *
for borrowed references, object
for not-borrowed ones):
from cpython.object cimport PyObject
from cpython.ref cimport Py_INCREF
cdef extern from "Python.h":
PyObject* PyList_GetItem(object list, Py_ssize_t index)
object PyObject_GetItem(object o, object key)
But that doesn't seem to work for stolen references (or was my thinking just wrong?):
from cpython.object cimport PyObject
cdef extern from "Python.h":
void PyList_SetItem(object list, Py_ssize_t i, PyObject *o)
cpdef void func(list lst, object item):
PyList_SetItem(lst, 0, <PyObject*>item)