How to display the reference count of an object using sys.getrefcount in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To display the reference count of an object using sys.getrefcount() in Python, you can do the following:

import sys

my_object = "Hello World"  # create an object

ref_count = sys.getrefcount(my_object)  # get the reference count
print(f"The reference count of my_object is {ref_count}")  # print the reference count

When the sys.getrefcount() function is called on an object, it returns the number of references to that object. In this example, we create an object my_object that contains the string “Hello World”. We then use sys.getrefcount() to get the reference count of my_object, and print the result.

Note that sys.getrefcount() returns the total number of references to an object, including any internal references created by the Python interpreter. Therefore, the value returned may be larger than you expect. Additionally, sys.getrefcount() can be slow and should generally be avoided except for debugging purposes.

Tags:

sys