Why aren't destructors guaranteed to be called on interpreter exit?

前端 未结 5 586
余生分开走
余生分开走 2020-11-30 08:58

From the python docs:

It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits.

5条回答
  •  盖世英雄少女心
    2020-11-30 09:35

    One example where the destructor is not called is, if you exit inside a method. Have a look at this example:

    class Foo(object):
        def __init__(self):
            print("Foo init running")
    
        def __del__(self):
            print("Destructor Foo")
    
    
    class Bar(object):
        def __init__(self):
            print("Bar1 init running")
            self.bar = self
            self.foo = Foo()
    
        def __del__(self):
            print("Destructor Bar")
    
        def stop(self):
            del self.foo
            del self
            exit(1)
    
    b = Bar()
    b.stop()
    

    The output is:

    Bar1 init running
    Foo init running
    Destructor Foo
    

    As we destruct foo explicitly, the destructor is called, but not the destructor of bar!

    And, if we do not delete foo explicitly, it is also not destructed properly:

    class Foo(object):
        def __init__(self):
            print("Foo init running")
    
        def __del__(self):
            print("Destructor Foo")
    
    
    class Bar(object):
        def __init__(self):
            print("Bar1 init running")
            self.bar = self
            self.foo = Foo()
    
        def __del__(self):
            print("Destructor Bar")
    
        def stop(self):
            exit(1)
    
    b = Bar()
    b.stop()
    

    Output:

    Bar1 init running
    Foo init running
    

提交回复
热议问题