Puzzling behaviour of Py_IncRef

Chris Angelico rosuav at gmail.com
Wed Jan 19 06:09:45 EST 2022


On Wed, Jan 19, 2022 at 10:00 PM Tony Flury via Python-list
<python-list at 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


More information about the Python-list mailing list