[Python-Dev] Borrowed and Stolen References in API

Nick Coghlan ncoghlan at gmail.com
Mon May 9 16:36:04 CEST 2011

On Fri, May 6, 2011 at 8:27 PM, Antoine Pitrou <solipsis at pitrou.net> wrote:
> On Fri, 06 May 2011 13:28:11 +1200
> Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
>> Amaury Forgeot d'Arc wrote [concerning the Doc/data/refcounts.dat file]:
>> > 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.
>> Yes, that's the whole point. When using a functon,
>> what you need to know is whether it borrows or steals
>> a reference.
> Doesn't "borrow" mean the same as "steal" in that context?
> If an API borrows a reference, I expect it to take it from me.

Input parameter, borrowed or new reference: caller retains ownership
and must still decref item
Input parameter, stolen reference: caller transfers ownership and must
NOT decref item (or must incref before call to guarantee lifecycle if
planning to continue using the object after the call)

Output parameter or return value, borrowed reference: caller does NOT
receive ownership and does not need to decref item, but needs to be
careful of lifecycle (and promote to a full reference with incref if
the borrowed reference may outlive the original)
Output parameter or return value, stolen or new reference: caller
receives ownership and must decref item

One interesting aspect is that from the caller's point of view, a
*new* reference to the relevant behaves like a borrowed reference for
input parameters, but like a stolen reference for output parameters
and return values. It is typically the converse cases (stolen
reference to an input parameter, borrowed reference to an output
parameter or return value) that requires special attention on the
caller's part.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-Dev mailing list