Skip to main content
3 of 3
deleted 316 characters in body

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)

    def __getattr__(self, attr):
        return getattr(self.file, attr)

    @classmethod
    def from_ntf(cls, named_temporary_file):
        """Creates a named file from the specified NamedTemporaryFile."""
        return cls(named_temporary_file.file, named_temporary_file.name)

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)))