I'm working with a temporary directory and I want to make sure that it gets deleted on program close (regardless of whether the program was successful). I'm using tempfile.mkdtemp
to create the directory and putting the string that's created into a subclass of str
that deletes the directory on its __del__
command:
import shutil
import tempfile
class TempDir(str):
""" container for temporary directory.
Deletes directory when garbage collected/zero references """
def __del__(self):
shutil.rmtree(self.__str__(), onerror=my_error_fn)
dbdir = TempDir(tempfile.mkdtemp())
Here's what I'm not sure about: if the program closes or a KeyboardInterrupt happens, will Python automatically delete/garbage collect all the variables? If not, how could I make sure that the directory gets deleted?
Related info about creating destructor methods in Python. Seems like so long as the TempDir object doesn't reference anything else, using __del__
to destruct it should be fine.
I wouldn't use a __del__
method, the semantics are unreliable, and could interfere with garbage collection. Use a context manager: define a __enter__
and __exit__
method, and put your use of the object in a with
statement. It's clear, it's explicit, and it will work without worry.
Or, another way to make a context manager:
@contextlib.contextmanager
def tempdir(prefix='tmp'):
"""A context manager for creating and then deleting a temporary directory."""
tmpdir = tempfile.mkdtemp(prefix=prefix)
try:
yield tmpdir
finally:
shutil.rmtree(tmpdir)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With