Please explain the meaning of 'stealing' a ref

Alex Martelli aleax at aleax.it
Tue Nov 4 09:20:18 EST 2003


Christos TZOTZIOY Georgiou wrote:
   ...
> Oh, definitely, ext/refcountsInPython.html is the page I believe.  I can
> understand the second paragraph, but I wanted some reasoning.  For
> example, you call a function that its API specifies that it "steals" a
> reference to its argument; therefore, you got to incref in advance and

Yes, you have to incref IF you want to keep owning that reference.

> decref afterwards yourself.  What's the reason?  Efficiency for

You'll decref when you don't want to own that reference any more,
and you incref'd it, but if you do that soon, why bother incref'ing?-)

The typical use case to explain the stealing is in the "Reference
Count Details" section of the API manual:

PyObject *t;

t = PyTuple_New(3);
PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
PyTuple_SetItem(t, 2, PyString_FromString("three"));


PyTuple_SetItem is very often called with a completely new reference
as its 3d argument, so it steals it to enable this easy idiom... w/o
the stealing you'd have to code, e.g.:

PyObject *t;
PyObject *temp;

t = PyTuple_New(3);

temp = PyInt_FromLong(1L);
PyTuple_SetItem(t, 0, temp);
Py_DECREF(temp);

etc -- much less handy.


> simplicity of the function?  If yes, why not enclose the function call
> in a incref / decref cycle and then export the enclosing function in the
> API?

I don't know what you're talking about.  Explain please?  E.g. with one
of the few reference-stealing functions, PyTuple_SetItem ?


> Such stuff I wanted to know.
> 
> Also, "borrowing" and "stealing" are the same thing?  I just think that

No!  You get a borrowed reference when you get a reference but are not
transferred the ownership of it.  That's a pretty widespread use regarding
references that are returned to objects that surely pre-existed.  You
must then incref in the relatively rare case you want to keep hold of
that reference for the longer term.

> "beautifying" terminology at the C level is more confusing than helpful.

What 'beautifying'...?


Alex





More information about the Python-list mailing list