I just realized, that I can simplify mktemp
by directly returning the tempfile._TemporaryFileWrapper
's buffer, which can be used in a file context for open and closing without deleting the superordinate _TemporaryFileWrapper
:
def mktemp(self, mode='w+b', encoding=None, suffix=''):
"""Creates and registers a named temporary
file and returns the file object.
"""
return self.enter_context(NamedTemporaryFile(
mode=mode, encoding=encoding, suffix=suffix, prefix=self.prefix,
dir=self.root)).file
Update
With the change above, the returned buffer does not behave as expected regarding its attribute name
.
To fix that, I introduced a wrapper class:
class NamedFile:
"""Wraps a file buffer and its associated name."""
def __init__(self, file, name):
"""Sets buffer and name."""
self.file = file
self.name = name
def __enter__(self):
self.file.__enter__()
return self
def __exit__(self, typ, value, traceback):
return self.file.__exit__(typ, value, traceback)
@classmethod
def from_ntf__getattr__(clsself, named_temporary_fileattr):
"""Creates a named file from the specified NamedTemporaryFile."""
return clsgetattr(named_temporary_fileself.file, named_temporary_file.nameattr)
@property@classmethod
def seekfrom_ntf(self):
"""Delegates seeking to the buffer."""
return self.file.seek
@property
defcls, read(selfnamed_temporary_file):
"""Delegates reading to the buffer."""
"""Creates a returnnamed self.file.read
@property
def write(self):
"""Delegates writing tofrom the bufferspecified NamedTemporaryFile."""
return selfcls(named_temporary_file.file, named_temporary_file.writename)
And return it instead of the raw buffer accordingly:
def mktemp(self, mode='w+b', encoding=None, suffix=''):
"""Creates and registers a named temporary
file and returns the file object.
"""
return NamedFile.from_ntf(self.enter_context(NamedTemporaryFile(
mode=mode, encoding=encoding, suffix=suffix, prefix=self.prefix,
dir=self.root)))