Is there a way to get the current ref count of an object in Python?

人盡茶涼 提交于 2019-11-27 04:19:05
tehvan

According to the Python documentation, the sys module contains a function:

import sys
sys.getrefcount(object) #-- Returns the reference count of the object.

Generally 1 higher than you might expect, because of object arg temp reference.

kquinn

Using the gc module, the interface to the garbage collector guts, you can call gc.get_referrers(foo) to get a list of everything referring to foo.

Hence, len(gc.get_referrers(foo)) will give you the length of that list: the number of referrers, which is what you're after.

See also the gc module documentation.

Frank-Rene Schäfer

There is gc.get_referrers() and sys.getrefcount(). But, It is kind of hard to see how sys.getrefcount(X) could serve the purpose of traditional reference counting. Consider:

import sys

def function(X):
    sub_function(X)

def sub_function(X):
    sub_sub_function(X)

def sub_sub_function(X):
    print sys.getrefcount(X)

Then function(SomeObject) delivers '7',
sub_function(SomeObject) delivers '5',
sub_sub_function(SomeObject) delivers '3', and
sys.getrefcount(SomeObject) delivers '2'.

In other words: If you use sys.getrefcount() you must be aware of the function call depth. For gc.get_referrers() one might have to filter the list of referrers.

I would propose to do manual reference counting for purposes such as “isolation on change”, i.e. “clone if referenced elsewhere”.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!