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 tempfile.mkdtemp() in the def __init__ to create the space, but I have read that I can’t rely on __del__ being called.
I am wanting something like this:
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)
Is there another/better way to handle this clean up? I was reading about with, but it appears to only be helpful within a function.
Caveat: you can never guarantee that the temp folder will be deleted, because the user could always hard kill your process and then it can’t run anything else.
That said, do
Since this is a very common operation, Python has a special way to encapsulate “do something, execute code, clean up”: a context manager. You can write your own as follows:
and use it as
(Note that this uses the
@contextlib.contextmanagershortcut to make a context manager. If you want to implement one the original way, you need to make a custom class with__enter__and__exit__methods; the__enter__would create and return the temp directory and the__exit__delete it.