CompoundDoc.XlsDoc.save() won't close files
Status: Alpha
Brought to you by:
rvk
The code looks like this:
... def save(self, filename, stream): ... f = filename if not hasattr(filename, 'write'): f = file(filename, 'wb') f.write(...) ... (neglect to close f)
The result is that, if run from a Python implementation other than CPython (e.g., pypy), the file is not closed.
I think the code needs to be correct in both cases when filename is a file object and when filename is a string. I'd suggest changing it like this:
def save(self, filename, stream): ... def _dowrite(): f.write(...) ... (still neglect to close f) f = filename if hasattr(filename, 'write'): _dowrite() else: with file(filename, 'wb') as f: _dowrite()
There is a similar problem in antlr.CharScanner.setInput(). Unluckily, that one really require keeping a state about whether the file is opened by setInput(), and there is an additional problem that it is hard to find the correct place to close the file.
Neglecting to close a file for reading is not as bad as neglecting to close a file for writing. For me, the problem of read comes when I read a file in NFS and then try removing the directory. Because the file is still opened, NFS turns the file to a dummy filename, but the file remains in the directory so the directory removal fail. For write it additionally means the file content might not have been flushed out.
The workaround is, of course, to open the file in the caller and pass the opened file to parse_xls() and save().