Reputation: 153
I read on this page: https://www.geeksforgeeks.org/destructors-in-python/ that the garbage collector detects cyclical references and removes them. If so, how come the cyclical reference in this code doesn't seem to get removed (I'm assuming that since the print statements don't raise an attribute error):
class A:
def __init__(self, other_instance):
self.other_instance = other_instance
def __repr__(self):
return 'A object'
class B:
def __init__(self):
self.other_instance = A(self)
def __repr__(self):
return 'B object'
obj = B()
print(obj.other_instance.other_instance)
print(obj.other_instance)
Am I missing something?
Upvotes: 0
Views: 79
Reputation: 280564
It detects and clears cyclical references in garbage - objects that are no longer reachable. Your objects are not garbage.
It is by design impossible to inspect objects at a point after the garbage collector has cleared their cyclical references, as doing so would require the objects to still be reachable.
(Note that the article you're reading is out of date, and it wasn't great even before then. The interaction between __del__
and the garbage collector doesn't work like the article describes any more.)
Upvotes: 1