python reference count 를 소개해보도록 하겠습니다. 이 내용을 읽어주시면 python reference count 를 이해하실 수 있으실 겁니다. reference count 이 궁금하다면 반드시 끝까지 읽어주세요. 이제 아래에서 모두 알려드리겠습니다.

 

python reference count

 

python reference count

reference count 란 파이썬의 모든 객체를 카운트하는 것을 의미하며

객체가 참조될 때 증가하고, 참조가 삭제되면 감소시키는 방식으로 동작합니다.

reference count 가 0이 되면 삭제 대상이 되며 삭제 cycle 이 되면 메모리 할당이 해제됩니다. (object is free!!)

 

아래 예시를 통해 reference count 가 변경되는 것을 확인해보자.

import sys

a = [1,2,3,4]
print(f'count {sys.getrefcount(a)}')
b = a
print(f'count {sys.getrefcount(a)}')
c = a
print(f'count {sys.getrefcount(a)}')
c = 0
print(f'count {sys.getrefcount(a)}')
b = 0
print(f'count {sys.getrefcount(a)}')

count 2
count 3
count 4
count 3
count 2

a 의 reference count 가 변경되는 것을 쉽게 확인할 수 있다.

 

아래는 내부에서 reference count 를 counting 하는 함수이다.

cpython/object.h 를 참고했다.

_Py_INCREF : Increase Reference Count

_Py_DECREF : Decrease Reference Count

c 계열 언어를 다뤄보지 않으셨어도 _Py_RefTotal++; _Py_RefTotal--; 등 포인트를 잘 보면 읽힐거라 생각합니다.

static inline void _Py_INCREF(PyObject *op)
{
#if defined(Py_REF_DEBUG) && defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000
    // Stable ABI for Python 3.10 built in debug mode.
    _Py_IncRef(op);
#else
    // Non-limited C API and limited C API for Python 3.9 and older access
    // directly PyObject.ob_refcnt.
#ifdef Py_REF_DEBUG
    _Py_RefTotal++;
#endif
    op->ob_refcnt++;
#endif
}
#define Py_INCREF(op) _Py_INCREF(_PyObject_CAST(op))

static inline void _Py_DECREF(
#if defined(Py_REF_DEBUG) && !(defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000)
    const char *filename, int lineno,
#endif
    PyObject *op)
{
#if defined(Py_REF_DEBUG) && defined(Py_LIMITED_API) && Py_LIMITED_API+0 >= 0x030A0000
    // Stable ABI for Python 3.10 built in debug mode.
    _Py_DecRef(op);
#else
    // Non-limited C API and limited C API for Python 3.9 and older access
    // directly PyObject.ob_refcnt.
#ifdef Py_REF_DEBUG
    _Py_RefTotal--;
#endif
    if (--op->ob_refcnt != 0) {
#ifdef Py_REF_DEBUG
        if (op->ob_refcnt < 0) {
            _Py_NegativeRefcount(filename, lineno, op);
        }
#endif
    }
    else {
        _Py_Dealloc(op);
    }
#endif
}

주석도 아주 잘 작성되어 있어서 관심이 있으시다면 참고해보셔도 좋을 듯 합니다.

직역하면.. Py_INCREF, Py_DECREF 를 통해 reference count 를 관리하고,

reference count 가 0 이 되면 standard function free() 를 실행하여 메모리를 해제한다는 내용입니다.

 

 

같이 보시면 좋은 문서

- https://docs.python.org/ko/3/extending/extending.html?highlight=reference%20count#reference-counts

 

 

python reference count 에 대해 알려드렸습니다. 모두 읽어주셔서 감사합니다. 다른 지식도 필요하시다면 상단의 글들을 참고하시면 도움이 될 것 같습니다. 이 글이 유용했다면 하트(공감), 댓글, 구독을 부탁드립니다.

반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기