Python will clean up object upon the reference count down to 0 if it is not strongly referred by other object.
We can clean up class objects by using weakref.finalize
. Avoid using the dunder __del__
for resource clean-up since such clean-up is not guarantee by the interpreter. It is shown as follow:
class TempDir:
def __init__(self):
# shutil.rmtree guarantees the object will be clean up by garbage collector
self._finalizer = weakref.finalize(self, shutil.rmtree, self.name)
def remove(self):
self._finalizer()
@property
def removed(self):
return not self._finalizer.alive
We can further guarantee a clean-up upon exception by utilising #202206071327:
# for `with ... as ...`
def __enter__(self):
return self
# for `with ... as ...`
def __exit__(self, exc_type, exc_val, exc_tb):
self.remove()