Python Resource Clean Up

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()
Links to this page
  • Python Context Management Protocol

    Python Context Management Protocol consists of one keyword and two dunder methods: with, __enter__() and __exit__(). It is proposed to replace the now legacy dunder __del__() for its inconsistency on 202206062313#. The class or function that implements the protocol is called a context manager.

#python #resource