Contrarian view on closing files
Horrendous advice on many levels<p>- reference counting is an implementation detail, it is not part of the spec<p>- that&#x27;s because real implementations exist where refcounting does not exist (ironpython, pypy, jython)<p>- even if it were part of the spec, the schedule for object destruction also is not part of the spec. Your file object was noticed as part of an unused graph at T+0, even mainline CPython can perpetually defer its destruction to T+infinity due to its handling of reference cycles<p>- the random system resource will eventually be garbage collected, but perhaps not if your code throws the wrong exception and&#x2F;or one of those cute syntax sugar libraries takes a reference to its frame object you know nothing about. Or how about pretty much any debugging support library like Sentry? Best to have audited them all..<p>- the random system resource was garbage a few tens of opcodes ago, but you left it locked, and some future change caused your code to immediately attempt to reopen and relock it. surprise, deadlock in production<p>The comparison with &#x27;dict.clear()&#x27; makes no sense whatsoever because explicit external resource control is <i>precisely</i> required because those external resources aren&#x27;t automatically managed like normal in-memory objects. They have material external state beyond whether they are allocated or deallocated, and require explicit initialization and de-initialization in order to avoid leaving them in unspecified states. Python&#x27;s memory allocator provides none of these behaviours as guarantees. It&#x27;s not even guaranteed to always call __del__, this is most commonly observable during interpreter shutdown.<p>Perhaps a better way of looking at it is this: try&#x2F;finally and with: exist for you to demand stronger guarantees from the runtime than it normally offers you. &quot;Hey Mr. Python, I know you&#x27;ll &#x2F;probably&#x2F; clean up this object eventually, but I also know there are 100 edge cases where you won&#x27;t bother. For this object, you are on the hook for every case, including the cases where I wrote buggy code&quot;<p>Meanwhile, feel free to follow this advice, and good luck at 4am debugging your prod system that for some inexplicable reason recently began crashing due to running out of file descriptors..