To read contents of a file:
data = open(filename, \"r\").read()
The open file immediately stops being referenced anywhere, so the file obje
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:
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.