I had always assumed that a file would leak if it was opened without being closed, but I just verified that if I enter the following lines of code, the file will close:
>>> f = open('somefile.txt') >>> del f
Just out of sheer curiosity, how does this work? I notice that file doesn’t include a __del__ method.
In CPython, at least, files are closed when the file object is deallocated. See the
file_deallocfunction inObjects/fileobject.cin the CPython source. Dealloc methods are sort-of like__del__for C types, except without some of the problems inherent to__del__.