title: Right way to clean up a temporary folder in Python class
body: <p>I am creating a class in which I want to generate a temporary workspace of folders that will persist for the life of the object and then be removed.  I am using <code>tempfile.mkdtemp()</code> in the <code>def __init__</code> to create the space, but I have read that I can't rely on <code>__del__</code> being called.</p>
  <p>I am wanting something like this:</p>
  <pre><code>class MyClass:
    def __init__(self):
      self.tempfolder = tempfile.mkdtemp()
  
    def ... #other stuff
  
    def __del__(self):
      if os.path.exists(self.tempfolder): shutil.rmtree(self.tempfolder)
  </code></pre>
  <p>Is there another/better way to handle this clean up?  I was reading about <code>with</code>, but it appears to only be helpful within a function.</p>