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

PythonRefcounting

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

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”.

Solution 4 - Python

import ctypes

my_var = 'hello python'
my_var_address = id(my_var)

ctypes.c_long.from_address(my_var_address).value

ctypes takes address of the variable as an argument. The advantage of using ctypes over sys.getRefCount is that you need not subtract 1 from the result.

Solution 5 - Python

Every object in Python has a reference count and a pointer to a type. We can get the current reference count of an object with the sys module. You can use sys.getrefcount(object), but keep in mind that passing in the object to getrefcount() increases the reference count by 1.

import sys

name = "Steve"

# 2 references, 1 from the name variable and 1 from getrefcount
sys.getrefcount(name)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAJ View Question on Stackoverflow
Solution 1 - PythontehvanView Answer on Stackoverflow
Solution 2 - PythonkquinnView Answer on Stackoverflow
Solution 3 - PythonFrank-Rene SchäferView Answer on Stackoverflow
Solution 4 - PythonGautam VanamaView Answer on Stackoverflow
Solution 5 - PythonUtkarshView Answer on Stackoverflow