Note that there are some explanatory texts on larger screens.

plurals
  1. POPython file objects, closing, and destructors
    primarykey
    data
    text
    <p>The description of <code>tempfile.NamedTemporaryFile()</code> says:</p> <blockquote> <p>If <em>delete</em> is true (the default), the file is deleted as soon as it is closed.</p> </blockquote> <p>In some circumstances, this means that the file is not deleted after the Python interpreter ends. For example, when running the following test under <code>py.test</code>, the temporary file remains:</p> <pre><code>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') </code></pre> <p>In some way this makes sense, because this program never explicitly closes the file object. The only other way for the object to get closed would presumably be in the <code>__del__</code> destructor, but here the language references states that "<em>It is not guaranteed that <code>__del__()</code> methods are called for objects that still exist when the interpreter exits.</em>" So everything is consistent with the documentation so far.</p> <p>However, I'm confused about the implications of this. If it is not guaranteed that file objects are closed on interpreter exit, can it possibly happen that some data that was successfully written to a (buffered) file object is lost even though the program exits gracefully, because it was still in the file object's buffer, and the file object never got closed?</p> <p>Somehow that seems very unlikely and un-pythonic to me, and the open() documentation doesn't contain any such warnings either. So I (tentatively) conclude that file objects are, after all, guaranteed to be closed.</p> <p>But how does this magic happen, and why can't <code>NamedTemporaryFile()</code> use the same magic to ensure that the file is deleted? </p> <p><em>Edit:</em> Note that I am not talking about file <em>descriptors</em> here (that are buffered by the OS and closed by the OS on program exit), but about Python file objects that may implement their own buffering.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload