Puzzling behaviour of Py_IncRef

Tony Flury tony.flury at btinternet.com
Thu Jan 27 02:46:11 EST 2022


On 26/01/2022 22:41, Barry wrote:
>
>
> Run python and your code under a debugger and check the ref count of 
> the object as you step through the code.
>
> Don’t just step through your code but also step through the C python code.
> That will allow you to see how this works at a low level.
> Setting a watch point on the ref count will allow you run the code and 
> just break as the ref count changes.
>
> That is what I do when a see odd c api behaviour.
>
> Barry


Thanks - I have tried a few times on a few projects to run a debugger in 
mixed language mode and never had any success.

I will have to try again.


>> As posted in the original message - immediately before the call to 
>> the C function/method sys.getrefcount reports the count to be 2 
>> (meaning it is actually a 1).
>>
>> Inside the C function the ref count is incremented and the Py_REFCNT 
>> macro reports the count as 3 inside the C function as expected (1 for 
>> the name in the Python code, 1 for the argument as passed to the C 
>> function, and 1 for the increment), so outside the function one would 
>> expect the ref count to now be 2 (since the reference caused by 
>> calling the function is then reversed).
>>
>> However - Immediately outside the C function and back in the Python 
>> code sys.getrefcount reports the count to be 2 again - meaning it is 
>> now really 1. So that means that the refcount has been decremented 
>> twice in-between the return of the C function and the execution of 
>> the immediate next python statement. I understand one of those 
>> decrements - the parameter's ref count is incremented on the way in 
>> so the same object is decremented on the way out (so that calls don't 
>> leak references) but I don't understand where the second decrement is 
>> coming from.
>>
>> Again there is nothing in the Python code that would cause that 
>> decrement - the decrement behavior is in the Python runtime.
>>
>>>> -- 
>>>> Anthony Flury
>>>> email :anthony.flury at btinternet.com
>>>>
>>>> -- 
>>>> https://mail.python.org/mailman/listinfo/python-list
>>>>
>> -- 
>> Anthony Flury
>> email :anthony.flury at btinternet.com

-- 
Anthony Flury
email : anthony.flury at btinternet.com



More information about the Python-list mailing list