reference count
In Python, the reference count is a mechanism that the interpreter uses to manage memory allocation and deallocation for objects. It’s a key element of the CPython implementation specifically, and other implementations may manage memory differently.
Every object in Python has an associated reference count, which keeps track of the number of references pointing to that object. When you create a new reference to an object, its reference count increases by one. In contrast, when a reference is deleted or goes out of scope, the reference count decreases by one.
Once the reference count drops to zero, the object is immediately deallocated. Not every object plays by this rule, though. Since Python 3.12, some objects are immortal, which means their reference count is never modified and they’re never deallocated.
For example, None, True, and False are immortal in CPython. Python’s separate cyclic garbage collector handles reference cycles that reference counting alone can’t reclaim.
Example
Here’s an example to demonstrate how reference counting works in Python:
>>> import sys
>>> greeting = "Hello, World!" # A reference to the string
>>> sys.getrefcount(greeting)
2
>>> value = greeting # Create a new reference, value
>>> sys.getrefcount(greeting)
3
>>> del value # Delete the value reference
>>> sys.getrefcount(greeting)
2
>>> del greeting # No more references (garbage collection time)
In this example, the sys.getrefcount() function returns the reference count for the object "Hello, World!". Note that the reference count is initially 2 because getrefcount() temporarily adds its own reference to the object. The exact numbers aren’t guaranteed, though.
The Python documentation warns against relying on sys.getrefcount() for an accurate value, other than 0 or 1, because immortal objects report a very large count that doesn’t match the number of references actually held. Reference counts can also differ between Python versions.
Related Resources
Tutorial
Memory Management in Python
Get ready for a deep dive into the internals of Python to understand how it handles memory management. By the end of this article, you’ll know more about low-level computing, understand how Python abstracts lower-level operations, and find out about Python’s internal memory management algorithms.
For additional information on related topics, take a look at the following resources:
- How Python Manages Memory (Course)
- Variables in Python: Usage and Best Practices (Tutorial)
- Python's del: Remove References From Scopes and Containers (Tutorial)
- Memory Management in Python (Quiz)
- Variables in Python (Course)
- Variables in Python: Usage and Best Practices (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.