Is there a way to get the current object reference count in Python?

Is there a way to get the current number of object references in Python?

+72
python
04 Feb '09 at 7:32
source share
3 answers

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

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

Overall 1 is higher than you might expect due to a reference to the arg temp object.

+86
04 Feb '09 at 7:39
source share

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

Therefore, len(gc.get_referrers(foo)) will give you the length of this list: the number of referees, which you are after.

See also gc documentation.

+57
Feb 04 '09 at 7:36
source share

There is gc.get_referrers() and sys.getrefcount() . But, it is hard to understand how sys.getrefcount(X) can 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) supplies "7",
sub_function(SomeObject) supplies "5",
sub_sub_function(SomeObject) supplies "3" and
sys.getrefcount(SomeObject) supplies '2'.

In other words: if you use sys.getrefcount() , you must know the depth of the function call. For gc.get_referrers() may need to filter the list of referrers.

I would suggest doing manual reference counting for purposes such as isolation when changing, i.e. "clone if referenced elsewhere."

+7
Dec 10 '16 at 23:00
source share



All Articles