[Python-Dev] Borrowed and Stolen References in API

Guido van Rossum guido at python.org
Thu May 5 19:00:54 CEST 2011


On Thu, May 5, 2011 at 3:38 AM, Amaury Forgeot d'Arc <amauryfa at gmail.com> wrote:
> Hi,
>
> Le jeudi 5 mai 2011, Greg Ewing <greg.ewing at canterbury.ac.nz> a écrit :
>> Amaury Forgeot d'Arc wrote:
>>
>>
>> It's in the file Doc/data/refcounts.dat
>> in some custom format.
>>
>>
>> However, it doesn't seem to quite convey the same information.
>> It lists the "refcount effect" on each parameter, but translating
>> that into the notion of borrowed or stolen references seems
>> to require knowledge of what the function does.
>>
>> For example, PyDict_SetItem has:
>>
>> PyDict_SetItem:PyObject*:p:0:
>> PyDict_SetItem:PyObject*:key:+1:
>> PyDict_SetItem:PyObject*:val:+1:
>>
>> All of these parameters take borrowed references, but the
>> key and val get incremented because they're being stored
>> in the dict.
>
> This is not always true, for example when the item is already present
> in the dict.
> It's not important to know what the function does to the object,
> Only the action on the reference is relevant.
>
>>
>> So this file appears to be of limited usefulness.

Seems you're in agreement with this. IMO when references are borrowed
it is not very interesting. The interesting thing is when calling a
function *steals* a reference. The other important thing to know is
whether the caller ends up owning the return value (if it is an
object) or not. I *think* you can tell the latter from the +1 for the
return value; but the former (whether it steals a reference) is
unclear from the data given. There's even an XXX comment about this in
the file:

# XXX NOTE: the 0/+1/-1 refcount information for arguments is
# confusing!  Much more useful would be to indicate whether the
# function "steals" a reference to the argument or not.  Take for
# example PyList_SetItem(list, i, item).  This lists as a 0 change for
# both the list and the item arguments.  However, in fact it steals a
# reference to the item argument!

-- 
--Guido van Rossum (python.org/~guido)


More information about the Python-Dev mailing list