On 19/01/2022 11:09, Chris Angelico wrote:
On Wed, Jan 19, 2022 at 10:00 PM Tony Flury via Python-list
<python-list@python.org> wrote:
Extension function :
static PyObject *_Node_test_ref_count(PyObject *self)
{
printf("\nIncrementing ref count for self - just for the hell
of it\n");
printf("\n before self has a ref count of %ld\n", Py_REFCNT(self));
Py_INCREF(self);
printf("\n after self has a ref count of %ld\n", Py_REFCNT(self));
fflush(stdout);
At this point, the refcount has indeed been increased.
return self;
}
And then you say "my return value is this object".
The normal thing to do is to add a reference to whatever you're
returning. For instance, Py_RETURN_NONE will incref None and then
return it.
So you're incrementing the refcount, then returning it without
incrementing the refcount. Your code is actually equivalent to "return
self".
In order to actually leak a reference, you'd need to incref it twice.
ChrisA
Chris - I am still puzzled - does doing 'return self' automatically
decrement the ref count of the object ?, and why is that the desired
behaviour ? Effectively it results in a decrement of two, since at the
exit of the function the ref count is only 1 (as witnessed by the
subsequent call to assertEqual).
(I am not suggesting that it should be changed - I understand that would
be a breaking change !).
You say I am returning it without incrementing, but I am explicitly
incrementing it before the return.
--
https://mail.python.org/mailman/listinfo/python-list