Search notes:

Python: Using ctypes to get an object's reference counter

This example tries to demonstrate how the ctypes module can be used to access an object's reference counter.
In CPython (Python's reference implementation), the built-in function id(obj) returns the memory address of the object that the variable obj references. In the sources of CPython, this address is the memory location of the object's reference counter (see definition of Include/object.h. Include/object.h)
So, in the following Python script, we create two references to an object and use this object's id() to directly access the memory where the reference counter is stored and then print it twice, once with one reference pointing tot the object and once with two references pointing to the object.
import ctypes

class CLS: pass

obj_ref_1 = CLS()

ob_refcnt = ctypes.c_long.from_address(id(obj_ref_1))

print(ob_refcnt.value)
#
# 1

obj_ref_2 = obj_ref_1

print(ob_refcnt.value)
#
# 2
Github repository about-Python, path: /standard-library/ctypes/ob_refcnt.py

See also

An alternative way to get an object's reference cuont is to use sys.getrefcount(obj).

Index