On Fri, Feb 10, 2012 at 4:32 AM, Tim Delaney <timothy.c.delaney@gmail.com> wrote:
On 10 February 2012 20:16, Dirkjan Ochtman <dirkjan@ochtman.nl> wrote:
open('foo').read()
With refcounting, the file will be closed soon. With garbage collection, it won't. Being able to rely on cleanup per frame/function call is pretty useful.
This is the #1 anti-pattern that shouldn't be encouraged. Using this idiom is just going to cause problems (mysterious exceptions while trying to open files due to running out of file handles for the process) for anyone trying to port your code to other implementations of Python.
It's not that open('foo').read() is "good". Clearly with the presence of nondeterministic garbage collection, it's bad. But it is convenient and compact. Refcounting GCs in general give very nice, predictable behavior, which lets us ignore a lot of the details of destroying things. Without something like this, we have to do some forms of resource management by hand that we could otherwise push to the garbage collector, and while sometimes this is as easy as a with statement, sometimes it isn't. For example, what do you do if multiple objects are meant to hold onto a file and take turns reading it? How do we close the file at the end when all the objects are done? Is the answer "manual refcounting"? Or is the answer "I don't care, let the GC handle it"? -- Devin