How to get reference count of a PyObject from C++? 
There are functions Py_INCREF and Py_DECREF which increase/decrease it, but I haven't found any function which return object's reference count.
I need it for debugging purposes.
Reference counting allows clients of your library to keep reference objects created by your library on the heap and allows you to keep track of how many references are still active.
If an object's reference count reaches zero, the object has become inaccessible, and can be destroyed. When an object is destroyed, any objects referenced by that object also have their reference counts decreased.
Reference counting in CPython At a very basic level, a Python object's reference count is incremented whenever the object is referenced, and it's decremented when an object is dereferenced. If an object's reference count is 0, the memory for the object is deallocated.
The reference count of each and every object is stored in the PyObject itself, in a variable called ob_refcnt. You can directly access that.
typedef struct _object {
    _PyObject_HEAD_EXTRA
    Py_ssize_t ob_refcnt;          # Reference count
    struct _typeobject *ob_type;
} PyObject;
Alternatively, you can use the Py_REFCNT Macro.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With