How a python object stores a garbage collection counter

I tried to figure out how python stores the object reference count:

getrefcount(...)
    getrefcount(object) -> integer

    Return the reference count of object.  The count returned is generally
    one higher than you might expect, because it includes the (temporary)
    reference as an argument to getrefcount().
    >>>

>>> s = 'string'
>>> sys.getrefcount(s)
28
>>> d = {'key' : s}
>>> sys.getrefcount(s)
29
>>> l = [s]
>>> sys.getrefcount(s)
30
>>> del l
>>> sys.getrefcount(s)
29
>>> del d
>>> sys.getrefcount(s)
28
>>>

In my above snippet, as soon as I create a string object s, I got a reference count of 28, and then when I assigned inside the dictionary its count counter to one. And I don't know why it starts at 28.

So here I am trying to figure out where these values ​​are stored or how python works.

thanks

+4
source share
3 answers

You can get a list of referrers to your object using gc.get_referrers, for example

import gc, pprint
pprint.pprint(gc.get_referrers("string"))

The reference count of each object is stored in the object itself, in a variable called ob_refcnt

typedef struct _object {
    _PyObject_HEAD_EXTRA
    Py_ssize_t ob_refcnt;
    struct _typeobject *ob_type;
} PyObject;

Py_INCREF Py_DECREF .

#define Py_INCREF(op) (                         \
    _Py_INC_REFTOTAL  _Py_REF_DEBUG_COMMA       \
    ((PyObject*)(op))->ob_refcnt++)

#define Py_DECREF(op)                                   \
    do {                                                \
        if (_Py_DEC_REFTOTAL  _Py_REF_DEBUG_COMMA       \
        --((PyObject*)(op))->ob_refcnt != 0)            \
            _Py_CHECK_REFCNT(op)                        \
        else                                            \
        _Py_Dealloc((PyObject *)(op));                  \
    } while (0)
+4

Python , . , .

, 'string' , 's', .

>>> s = 'string'
>>> sys.getrefcount(s)
2
>>> a = 'string'
>>> sys.getrefcount(s)
3
>>> b = 'string'
>>> sys.getrefcount(s)
4
+2

C-level ob_refcnt ob_base C, . , , - obj.ob_base.ob_refcnt.

PyObject . , PEP 3123 PyObject PyObject_HEAD, . , , .

0

Source: https://habr.com/ru/post/1526901/


All Articles