refcounting

"Martin v. Löwis" martin at v.loewis.de
Tue Apr 13 18:06:34 EDT 2004


Simon Dahlbacka wrote:

> I'm a little confused about the reference counting..
> 
> static PyObject* MyFunction(PyObject * /*self*/, PyObject *args) {
> 
> PyObject *list;
> PyArg_ParseTuple(args, &PyList_Type, &list);
> 
> //do stuff with list elements
> 
> // XXX do I need Py_INCREF(list); here ???
> return list;

Yes. PyArg_ParseTuple returns a borrowed reference to the list; the
reference is originally help by the argument tuple (which is immutable,
so the reference is guaranteed to stay while you hold on to the argument
tuple, which is only decrefed in the caller of MyFunction).

The result must be a new reference, so you must incref.

> PS. are there any documentation explaining the reference counting issues in
> more detail than the docs @ python.org ?

No. For the specific issue, the documentation says it all:

http://docs.python.org/api/arg-parsing.html

says

"O" (object) [PyObject *] ... The object's reference count is not increased.

http://docs.python.org/api/common-structs.html#l2h-821

says

PyCFunction ... The function must return a new reference.

HTH,
Martin




More information about the Python-list mailing list