tuple creation in C extensions

Thomas Wouters thomas at xs4all.net
Thu Jun 15 09:15:19 EDT 2000


On Thu, Jun 15, 2000 at 11:15:38AM +0000, Louis M. Pecora wrote:
> In article <200006141705.NAA14660 at w20-575-109.mit.edu>, Alexander S
> Coventry <alex_c at MIT.EDU> wrote:

> > > The docs already have that:
> > > 
> > >    PyObject* PyList_GetItem (PyObject *list, int index)
> > > 
> > >    Return value: Borrowed reference.
> 
> Oy, Vey!  Borrowed reference (if you know that) means you "manually"
> increase the refcount, right?  New ref. means you decrease the
> refcount, unless that item is returned to the Python calling routine?

Yes. Borrowed reference means you can use it for a little while, for
instance to pass it to a function that doesn't steal a reference, but if you
hang on to it for a while (executing code that might trigger changes in the
object you borrowed it from) you should INCREF it.

New reference means you get a new object, and if you 'throw it away', you
should DECREF it. But if you pass it on, make sure whoever you pass it to
knows it has to DECREF it (the parent function, usually, or one of the
'stealing' functions.)

> I'm sure there's more than this. :-)

Well, yes :) A couple of functions 'steal' references. They take a PyObject
as an argument, and they do not return a PyObject, and they do not INCREF
themselves -- they steal your reference. You should INCREF the object
(*before* passing it to such a function!) if you want to keep using it
yourself.

That's about it, though. The functions that don't have a comment about
references do not return a reference, and do not steal the references to
passed-in objects. (They may INCREF and DECREF them, but never take your
reference away.) If you write a container-object, something that should hold
on to another object, you have to INCREF that other object. If you remove
the object from the container, you should DECREF it, unless you plan on
passing it on. If you retrieve the object from the container, but do not
remove it from the container, you should INCREF it before passing it on.

Unless you define your functions to steal or return borrowed references
ofcourse ;) In which case I streneously suggest you document them properly,
in full view of yourself, before you shoot yourself in the foot with one of
your own functions. 

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list