How do I correctly clean up a Python object?

后端 未结 10 1127
北荒
北荒 2020-11-22 16:59
class Package:
    def __init__(self):
        self.files = []

    # ...

    def __del__(self):
        for file in self.files:
            os.unlink(file)
         


        
10条回答
  •  执念已碎
    2020-11-22 17:35

    Just wrap your destructor with a try/except statement and it will not throw an exception if your globals are already disposed of.

    Edit

    Try this:

    from weakref import proxy
    
    class MyList(list): pass
    
    class Package:
        def __init__(self):
            self.__del__.im_func.files = MyList([1,2,3,4])
            self.files = proxy(self.__del__.im_func.files)
    
        def __del__(self):
            print self.__del__.im_func.files
    

    It will stuff the file list in the del function that is guaranteed to exist at the time of call. The weakref proxy is to prevent Python, or yourself from deleting the self.files variable somehow (if it is deleted, then it will not affect the original file list). If it is not the case that this is being deleted even though there are more references to the variable, then you can remove the proxy encapsulation.

提交回复
热议问题