Description tempfile.NamedTemporaryFile() says:
If delete is true (the default), the file is deleted as soon as it closes.
In some cases, this means that the file is not deleted after the Python Translator finishes. For example, when performing the following test in py.test , the temporary file remains:
from __future__ import division, print_function, absolute_import import tempfile import unittest2 as unittest class cache_tests(unittest.TestCase): def setUp(self): self.dbfile = tempfile.NamedTemporaryFile() def test_get(self): self.assertEqual('foo', 'foo')
In a way, this makes sense because this program never explicitly closes the file. The only way to close the object is supposed to be in the __del__ destructor, but here the link language claims that "it is not guaranteed that the __del__() methods for objects that still exist when the translator exits. Everything is still consistent with the documentation.
However, I am confused about the consequences of this. If it’s not that the file’s objects are closed at the interpreter’s output, can it possibly be that some data that was successfully written to the (buffered) file object is lost, although the program exits gracefully because it was still in the object object buffer, and the object the file never closed?
Somehow it seems very unlikely and non-pythic to me, and open () in the documentation also does not have such warnings. So I (tentatively) conclude that file objects are, after all, guaranteed to be private.
But how does this magic happen, and why can't NamedTemporaryFile() the same magic to make sure the file is deleted?
Edit: note that I'm not talking about file descriptors here (which the OS buffers and the OS closes when the program exits), but Python files that can implement their own buffering.