Puzzling behaviour of Py_IncRef

Chris Angelico rosuav at gmail.com
Wed Jan 26 03:20:30 EST 2022


On Wed, 26 Jan 2022 at 19:04, Tony Flury via Python-list
<python-list at python.org> wrote:
>
> So according to that I should increment twice if and only if the calling
> code is using the result - which you can't tell in the C code - which is
> very odd behaviour.

No, the return value from your C function will *always* have a
reference taken. Whether the return value is "used" or just dropped,
there's always going to be one ref used by the returning itself.

The standard way to return a value is always to incref it, then return
the pointer. That is exactly equivalent to Python saying "return
<thing>".

Incrementing twice is ONLY because you want to leak a reference.

ChrisA


More information about the Python-list mailing list