Python sys.getrefcount() method
The Python sys.getrefcount() method returns the reference count for an object. The reference count indicates the number of references points to the object in memory. This method is useful for debugging memory management issues and understanding object lifespan in Python's memory.
When this method is called, it returns the count as an integer, which is typically higher than expected due to the temporary reference created by the function call.
Syntax
Following is the syntax and parameters of Python sys.getrefcount() method −
sys.getrefcount(object)
Parameter
This function accepts an object for which you want to get the reference count.
Return value
This method returns the reference count for an object.
Example 1
Following is the basic example that retrieves the reference count of the integer 42 and the exact count may vary depending on the Python implementation and platform −
import sys a = 42 print(sys.getrefcount(a))
Output
1000000005
Example 2
This example shows the reference count of a list object. The count is at least 2 because of the reference from the variable lst and the temporary reference passed to sys.getrefcount() −
import sys lst = [1, 2, 3] print(sys.getrefcount(lst))
Output
2
Example 3
This example shows the reference count of a string object. The count can be higher due to internal optimizations like interning of strings.−
import sys s = "hello" print(sys.getrefcount(s))
Output
4
Example 4
This example defines a function that prints the reference count of an object. The reference count includes the reference from the argument in the function scope.−
import sys
def check_refcount(obj):
print(sys.getrefcount(obj))
b = [4, 5, 6]
check_refcount(b)
Output
4
python_modules.htm