Python cyclic garbage collector example

Share Your Love

Here’s an example that demonstrates the cyclic garbage collector in Python:

import gc

class Node:
    def __init__(self, data): = data = None

# Create a circular linked list
node1 = Node(1)
node2 = Node(2)
node3 = Node(3) = node2 = node3 = node1

# Remove references to the circular linked list
node1 = None
node2 = None
node3 = None

# Manually trigger garbage collection

# Check if circular linked list objects are collected
for obj in gc.get_objects():
    if isinstance(obj, Node):
        print(f"Object {} is reachable")
        print(f"{obj} is unreachable")

# Output:
# <built-in function gc.collect> is unreachable
# Object 1 is reachable
# Object 2 is reachable
# Object 3 is reachable

In the example above, we create a circular linked list where each node points to the next node, and the last node points back to the first node, forming a cycle. After creating the circular linked list, we remove all references to the nodes by setting them to None. Then, we manually trigger garbage collection using gc.collect().

Finally, we iterate over the objects tracked by the garbage collector using gc.get_objects() and check if any objects of type Node (representing the circular linked list) are still reachable. In the output, we can see that objects with data values 1, 2, and 3 are still reachable, indicating that the cyclically referenced objects were not collected.

This demonstrates the behavior of the cyclic garbage collector, which cannot automatically detect and collect cyclically referenced objects in all cases. It’s important to break reference cycles manually by removing or breaking references between objects when you no longer need them to ensure proper memory management.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter