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

前端 未结 5 587
余生分开走
余生分开走 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:43

    If you did some nasty things, you could find yourself with an undeletable object which python would try to delete forever:

    class Phoenix(object):
        def __del__(self):
            print "Deleting an Oops"
            global a
            a = self
    
    a = Phoenix()
    

    Relying on __del__ isn't great in any event as python doesn't guarantee when an object will be deleted (especially objects with cyclic references). That said, perhaps turning your class into a context manager is a better solution ... Then you can guarantee that cleanup code is called even in the case of an exception, etc...

提交回复
热议问题