@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)
How do you manage a temporary directory such that it is guaranteed to be deleted on program close?