I implemented a context manager to handle temporary files and directories.
"""Temporary data management."""
from contextlib import ExitStack
from tempfile import template, NamedTemporaryFile, TemporaryDirectory
__all__ = ['TemporaryDataContext']
class TemporaryDataContext(ExitStack):
"""A context manager for temporary files and folders."""
def __init__(self, root=None, prefix=template):
"""Initializes the context manager with an
optional temporary data root and prefix.
"""
super().__init__()
self.root = root
self.prefix = prefix
def mktemp(self, mode='w+b', encoding=None, suffix=''):
"""Creates and registers a named temporary
file and returns the file object.
"""
temp = self.enter_context(NamedTemporaryFile(
suffix=suffix, prefix=self.prefix, dir=self.root))
temp.file.close()
return open(temp.name, mode=mode, encoding=encoding)
def mkdtemp(self, suffix=''):
"""Creates and registers a temporary
directory and returns its path.
"""
return self.enter_context(TemporaryDirectory(
suffix=suffix, prefix=self.prefix, dir=self.root))
It is being invoked by a data processing API to arbitrarily create temporary files and directories, that need to survive the entire processing chain and will be cleaned up at the end.
I am especially interested in optimizing the mktemp
method, which seems awkward to me (though it does its job).