File Open: Is This Bad Python Style?
Solution 1:
Just for the record: This is only slightly longer, and closes the file immediately:
from __future__ import with_statement
withopen(filename, "r") as f:
data = f.read()
Solution 2:
It is true that it will close eventually, but eventually might not be soon enough. Especially if you're using this inside a loop, the system might run out of file handles before the GC gets to the file objects.
Solution 3:
The code works exactly as you say it does, but it's bad style nevertheless. Your code relies on assumptions which may be true now, but won't always be true. It's not impossible that your code will be run in a situation where the file being opened and not close does matter. Is it really worth that risk just to save 1 or 2 lines of code? I don't think so.
Solution 4:
No, it's perfectly reasonable Python style IMO, as per your reasoning.
Update: There are a lot of comments here about whether file objects get tidied up straight away or not. Rather than speculate, I did some digging. Here's what I see:
From a comment in Python's
object.h
:
The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrement reference counts. Py_DECREF calls the object's deallocator function when the refcount falls to 0
Looking in Python's fileobject.c
:
The function table for file objects points to function file_dealloc
. This function
calls close_the_file
, which in turn closes the file.
So it seems reasonable to state that at the moment, on CPython, when there are no more references to a file object, it's closed without any delay. If you think this interpretation is wrong, please post a comment indicating why you feel that way.
Solution 5:
Even though it works as expected, I think it fails in two counts:
- Your code will not scale up seamlessly, because you are reading the entire file into memory, and this may or may not be necessarily what you want.
- According to the Zen of Python (try
import this
in the Python prompt to retrieve it) "explicit is better than implicit" and, by failing to explicitly close the file, you could confuse someone who, down the road, will be left with your code for maintenance.
It really helps being explicit! Python encourages explicit style.
Other than that, for a throwaway script, your style makes sense.
Maybe you will benefit from this answer.
Post a Comment for "File Open: Is This Bad Python Style?"