4

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.

Jokyjo
  • 144
  • 1
  • 8
  • FYI you can get the refcount in a less hacky manner via `sys.getrefcount`. The `gc` module also contains several functions that can be used to dissect GC behavior. –  Mar 29 '14 at 17:16

1 Answers1

3

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.

haraprasadj
  • 1,059
  • 1
  • 8
  • 17