How to Get The Current Reference Count of an Object in Python?

5/5 - (1 vote)

The reference count is the number of times an object is referenced by a variable. If an object isn’t referenced anymore, it can be safely removed from the memory—what’s the use of an object nobody cares for anyway? This article shows you how to count the number of references to a Python object.

What’s the Current Reference Count of Python Object

Question: How to get the current reference count of a Python object?

Get Reference Count Object Python

Answer: You can get the current reference count with the sys module’s getrefcount() method. For example, to get the number of times variable x is referenced, run sys.getrefcount(x).

Here’s the general strategy for an arbitrary object:

import sys

The following code snippet shows an example of an object x that has a reference count of 13. After creating a new reference y to the object x, the reference count increases by one to 14.

import sys

x = 42

# 13

y = x

# 14

You may not have expected that the initial reference count is 13. So, why is that? Let’s see.

Why is the Reference Count Higher Than Expected?

Reason 1: Implicit Helper Variables

Python is a high-level programming language. It provides you many convenience functions and memory management. You don’t have to care about the concrete memory locations of your objects and Python automatically performs garbage collection—that is—removing unused objects from memory. To do all of this work, Python relies on its own structures. Among those, are helper variables that may refer to an object you’ve created. All of this happens under the hood, so even if you don’t refer an object in your code, Python may still have created many references to that object. That’s why the reference count can be higher than expected.

Reason 2: Temporary Reference in getrefcount()

Note that by calling the function getrefcount(x), you create an additional temporary reference to the object x. This alone increases the reference counter by one.