Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get reference count of a PyObject?

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.

like image 338
DLunin Avatar asked Oct 01 '14 05:10

DLunin


People also ask

What is reference counting in compiler design?

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.

What happens when an object's reference count is zero?

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.

Does Python use reference counting?

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.


1 Answers

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.

like image 139
thefourtheye Avatar answered Sep 21 '22 13:09

thefourtheye