Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python C-API functions that borrow and steal references

The standard convention in the Python C-API is that

  • functions do not steal references from input arguments (that are objects)

  • return values and output arguments (that are objects) own a reference

Most functions in the Python C-API follow this convention. However, there are some exceptions. I have come across the following:

Functions that steal a reference from an input argument

PyModule_AddObject

Functions with return values or output arguments that borrow a reference

PyErr_Occurred
PyTuple_GetItem
PyTuple_GETITEM
PyDict_GetItem
PyDict_GetItemString
PyDict_Next

Is there a comprehensive list of such functions anywhere? Such a list would be a useful reference when writing Python extension modules.

like image 821
Johan Råde Avatar asked Apr 20 '12 14:04

Johan Råde


2 Answers

A text search in the Python 2.7.2 C-API docs for the words "steal" and "borrow" gave the following lists:

Functions that steal a reference from an input argument

PyCell_SET (but not PyCell_Set)
PyList_SetItem, PyList_SET_ITEM
PyModule_AddObject
PyTuple_SetItem, PyTuple_SET_ITEM

Functions with return values or output arguments that borrow a reference

all PyArg_Xxx functions
PyCell_GET (but not PyCell_Get)
PyDict_GetItem
PyDict_GetItemString
PyDict_Next
PyErr_Occurred
PyEval_GetBuiltins
PyEval_GetFrame
PyEval_GetGlobals
PyEval_GetLocals
PyFile_Name
PyFunction_GetClosure
PyFunction_GetCode
PyFunction_GetDefaults
PyFunction_GetGlobals
PyFunction_GetModule
PyImport_AddModule
PyImport_GetModuleDict
PyList_GetItem, PyList_GETITEM
PyMethod_Class, PyMethod_GET_CLASS
PyMethod_Function, PyMethod_GET_FUNCTION
PyMethod_Self, PyMethod_GET_SELF
PyModule_GetDict
PyObject_Init
PyObject_InitVar
PySequence_Fast_GET_ITEM
PySys_GetObject
PyThreadState_GetDict
PyTuple_GetItem, PyTuple_GET_ITEM
PyWeakref_GetObject, PyWeakref_GET_OBJECT
Py_InitModule
Py_InitModule3
Py_InitModule4
like image 105
Johan Råde Avatar answered Nov 04 '22 05:11

Johan Råde


This thread on the Python-Dev strongly suggests that such a list does not exist. The thread also discusses what to do about it.

like image 1
Steven Rumbalski Avatar answered Nov 04 '22 04:11

Steven Rumbalski