3 ms·
By automatic closing do you mean not at all and expecting the GC to do it? Or with a context manager. I think trusting an implementation detail of the underlyi
by tcbasche 6y ago
By automatic closing do you mean not at all and expecting the GC to do it? Or with a context manager.
I think trusting an implementation detail of the underlying interpreter is lazy at best and an anti-pattern at worst. We should aim to show our intent as much as possible, and closing a file or using a context manager certainly expresses our intent.
- shawnz 6y agoI mean imagine a hypothetical language where it was idiomatic to let the GC close files for you and the language was specified in such a way that it was guaranteed to work efficiently and wasn't just an implementation detail. Would code in that language have lower code quality than code in a language where files have to be closed manually? That's what the other poster seemed to be implying, but I think the opposite is true
- nemetroid 6y agoI don’t quite see what you mean by ”efficiently”. A language where garbage collection of file objects is guaranteed to happen within N milliseconds? The issue is holding on to an external resource for longer than needed. and by definition, garbage collection is deferred cleanup.
- shawnz 6y agoI mean "efficiently" in the sense that the consequences of having extraneous open file objects are managed appropriately so they don't blow up the system. I don't think that necessarily means collecting them all right away, but that's one option
- tsimionescu 6y agoWell, for many resources I would agree with you, but for files specifically, closing a file usually does a lot of things, which the article completely forgets about. In particular, write buffers are almost never flushed unless you do it explicitly or on file handle close.