After passing open call as argument to another function, is the file object closed?
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Melt
--
Chapters
00:00 After Passing Open Call As Argument To Another Function, Is The File Object Closed?
00:58 Accepted Answer Score 12
03:05 Thank you
--
Full question
https://stackoverflow.com/questions/1937...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 12
It's a poor practice. It has nothing to do with the open mode (read, write, read+write, append, binary mode, text mode ...).
In CPython, "it almost always works" because file objects are automatically closed when they become garbage (unreachable), and CPython's reference counting usually collects (non-cyclic) garbage very soon after it becomes garbage.
But relying on that is indeed poor practice.
If, for example, dosomething(f) runs for an hour before it returns, chances are excellent the file object will remain open the entire time.
Note: in some cases, dosomething(f) may be coded to explicitly close the passed-in file object itself. In those cases, it's not poor practice ;-)
Later: a related thing I've often seen is this:
data = open(file_path).read()
In CPython, the unnamed file object is garbage-collected (and so also closed) immediately when the statement completes, thanks to CPython's reference-counting. People are then surprised when they move their code to a different Python implementation, and get OS "too many open files!" complaints. Heh - serves 'em right ;-)
Example:
open("Output.txt", "w").write("Welcome")
print open("Output.txt").read()
This prints
Welcome
in CPython, because the unnamed file object from the first statement is garbage-collected (and closed) immediately when the first statement ends.
But:
output = open("Output.txt", "w")
output.write("Welcome")
print open("Output.txt").read()
probably prints an empty line in CPython. In this case, the file object is bound to a name (output), so is not garbage collected when the second statement completes (a smarter implementation could theoretically detect that output is never used again, and garbage-collect right away, but CPython does not).
"Welcome" is probably still in the file's memory buffer, so is not yet written to disk. So the third statement probably finds an empty file, and prints nothing.
In other implementations of Python, both examples may well print empty lines.