Reputation: 5415
In this example:
class Foo(object):
def __del__(self):
print "Foo died"
class Bar(object):
def __init__(self):
self.foo = Foo()
self.baz = Baz(self)
class Baz(object):
def __init__(self, bar):
self.bar = bar
b = Bar()
I'd expect the Foo destructor to be called in spite of the loop between Bar and Baz, as since Foo holds no references to any bar or baz collecting them and decrementing reference counts should be completely safe to do before collecting Foo. Why doesn't python behave this way? How can destructors possibly be useful if they can be prevented from being called by completely unrelated actions of other classes?
Upvotes: 0
Views: 181
Reputation: 309929
Note that the destructor does not need to be called when the interpreter exits.
A quick modification to your script and all works as you expected:
class Foo(object):
def __del__(self):
print "Foo died"
class Bar(object):
def __init__(self):
self.foo = Foo()
self.baz = Baz(self)
class Baz(object):
def __init__(self, bar):
self.bar = bar
b = Bar()
del b
Upvotes: 1