pythonctypesrefcounting

Strange behaviour of ref counter with ints being 0


I was fiddling with the ctypes module of python to better understand how the garbage collector works. Playing in the interpreter, I came through this strange situation :

>>>import ctypes
>>>def get_ref(obj):
...    """ This returns the refcount of obj as a c_size_t """
...    return ctypes.c_size_t.from_address(id(obj))
...
>>>myInt = 0
>>>get_ref(myInt)
c_ulong(283L)

Why does it seem that myInt is referenced 283 times by Python ? Have I missed something ?

Thanks for your insights.


Solution

  • In the CPython implementation of int, the references to [-5 ; 256] are shared.

    If you use myInt = 257, you should get a result of c_ulong(1L) as expected.

    Please see this link for details.