0

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?

Shea Levy
  • 5,237
  • 3
  • 31
  • 42

1 Answers1

1

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
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Oh! Well now I feel dumb. I assumed it would work the same as when I didn't have the `self.baz` line. Thanks, will mark as accepted when the time limit ends. – Shea Levy Jan 31 '13 at 14:34