Puzzling behaviour of Py_IncRef

Greg Ewing greg.ewing at canterbury.ac.nz
Wed Jan 26 01:57:54 EST 2022


The convention for refcounting in CPython is that a function
takes borrowed references as arguments and returns a new
reference.

The 'self' argument passed in is a borrowed reference. If you
want to return it, you need to create a new reference by
increfing it.

So what you have written is just the correct way to write
a do-nothing function that returns its argument, i.e. the
equivalent of the Python function

    def f(self):
       return self

As others have said, if you want to leak a reference, you
need an extra incref besides the one that's a normal part
of the return convention.

-- 
Greg



More information about the Python-list mailing list