Do you think garbage collector can track all the Python objects?

The garbage collector in Python can track most objects, but it focuses specifically on unreachable objects (reference count of zero) and objects involved in circular references. Understanding when and how garbage collection works is crucial for memory management.

What is a Garbage Collector?

The garbage collector is an automatic process that handles memory allocation and deallocation, ensuring efficient memory usage. Python uses reference counting as its primary memory management mechanism, with garbage collection as a backup for special cases.

We can interact with the garbage collector explicitly using the gc module. By default, it is enabled, but you can disable it if your code doesn't create circular references.

Objects with Reference Count Zero

Python's memory manager tracks the number of references to each object. When the reference count reaches zero, the object becomes unreachable and is immediately destroyed through reference counting ? not garbage collection.

Example

Here's how reference counting works with multiple references ?

import sys

class MyClass:
    def __init__(self, data):
        self.data = data
    
    def __del__(self):
        print("Object is being destroyed")

# Create object with two references
obj1 = MyClass([1, 2, 3, 4, 5])
obj2 = obj1

# Check reference count (+1 due to getrefcount() itself)
print("References of obj1:", sys.getrefcount(obj1))

# Delete first reference
del obj1
print("Deleted obj1")

# Delete second reference - triggers destruction
del obj2
print("Deleted obj2")
References of obj1: 3
Deleted obj1
Object is being destroyed
Deleted obj2

Objects with Circular References

Circular references occur when objects reference each other in a loop. These objects maintain non-zero reference counts even when unreachable from the program, requiring garbage collection to clean them up.

Example

This example demonstrates circular reference detection and cleanup ?

import gc

class Node:
    def __init__(self, name):
        self.name = name
        self.ref = None
    
    def __del__(self):
        print(f"Node {self.name} destroyed")

# Create circular reference
node1 = Node("A")
node2 = Node("B")
node1.ref = node2
node2.ref = node1

print("Created circular reference")
print("Objects before cleanup:", len(gc.get_objects()))

# Remove our references
node1 = None
node2 = None

print("Removed variables, running garbage collection...")
collected = gc.collect()
print(f"Collected {collected} objects")
Created circular reference
Objects before cleanup: 12847
Removed variables, running garbage collection...
Node A destroyed
Node B destroyed
Collected 2 objects

What Objects Can't Be Tracked?

The garbage collector cannot track certain objects:

  • Atomic types: integers, floats, strings (handled by reference counting)
  • Objects with __del__ methods: in circular references (Python < 3.4)
  • Extension objects: some C extensions may not be trackable

Example

Checking which objects are tracked ?

import gc

# These are NOT tracked by gc
number = 42
text = "hello"
simple_tuple = (1, 2, 3)

# These ARE tracked by gc
data_list = [1, 2, 3]
data_dict = {"key": "value"}
custom_obj = object()

print("Tracked objects include:")
tracked_count = 0
for obj in gc.get_objects():
    if obj is data_list:
        print("- List found in tracked objects")
        tracked_count += 1
    elif obj is data_dict:
        print("- Dictionary found in tracked objects") 
        tracked_count += 1
    elif obj is custom_obj:
        print("- Custom object found in tracked objects")
        tracked_count += 1

print(f"Total tracked objects: {len(gc.get_objects())}")
Tracked objects include:
- List found in tracked objects
- Dictionary found in tracked objects
- Custom object found in tracked objects
Total tracked objects: 12843

Conclusion

The garbage collector tracks container objects that can participate in circular references, but relies on reference counting for simple objects. Understanding this distinction helps in writing memory-efficient Python code.

---
Updated on: 2026-03-24T19:56:38+05:30

272 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements