[Python-Dev] Py_BuildValue and decref

Greg Ewing greg.ewing at canterbury.ac.nz
Sun Sep 10 09:35:59 CEST 2006

Barry Warsaw wrote:
> I just want to point out that the C API documentation is pretty  
> silent about the refcounting side-effects in error conditions (and  
> often in success conditions too) of most Python functions.  For  
> example, what is the refcounting side-effects of PyDict_SetItem() on  
> val?  What about if that function fails?  Has val been incref'd or  
> not?  What about the side-effects on any value the new one replaces,  
> both in success and failure?

The usual principle is that the refcounting behaviour
is (or should be) independent of whether the function
succeeded or failed. In the absence of any statement
to the contrary in the docs, you should be able to
assume that.

The words used to describe the refcount behaviour of
some functions can be rather confusing, but it always
boils down to one of two cases: either the function
"borrows" a reference (and does its own incref if
needed, the caller doesn't need to care) or it "steals"
a reference (so the caller is always responsible for
doing an incref if needed before calling).

What that rather convoluted comment about PyTuple_SetItem
is trying to say is just that it *always* steals a reference,
regardless of whether it succeeds or fails. I expect the
same is true of Py_BuildValue.


More information about the Python-Dev mailing list