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?
Answer: You can get the current reference count with the
getrefcount() method. For example, to get the number of times variable
x is referenced, run
Here’s the general strategy for an arbitrary
import sys print(sys.getrefcount(object))
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 print(sys.getrefcount(x)) # 13 y = x print(sys.getrefcount(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
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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.