I suspect people are talking about slightly different things. I'll try to make my understanding very explicit, so that people can jump on the parts they disagree with. (1) Python does not guarantee that it will clean up for you. If an object has a __del__ method, then this method will be run when the object is finalized -- but python might decide to never finalize the object. For example, if there are two objects in a cycle, and both have a __del__ method, then python may decide to make them immortal, so that it doesn't have to decide which __del__ to run first. (2) It is fairly common to have a resource which should be closed/released when you are done. (Example: a file). Normally, the garbage collector will do this for you -- it might even do so in all your tests, but not in production. If you want to *ensure* that your files are flushed and closed, you have to do it yourself, because python might choose not to collect them, even though it could. This is bug-prone. (a) It is easy to forget (and the problem may not show up in tests, because the garbage collection will *usually* work). (b) Calling a finalizer (such as close) explicitly means you can call it before all references are truly gone. (3) The closest thing there is to a safe idiom today is to emulate lisp's with-open-* macros using try/finally. try: f = open("filename") # if you do catch exceptions, then finally will have to # be replaced with a bare except and a reraise, plus an # else clause finally: f.close() (4) Proponents would like a way of saying "objects like this should *always* get their finalizer called". In return, they're willing to say "this is a temporary object that will not be returned from the local scope." If you replaced f() with f() gc() then any such objects created in f should have their __del__ methods run now. Even if they do appear in cycles. Even if they are referenced by an uncollectable object, such as an old extension class. (5) As proposed, it would be the user's responsibilibity to ensure that running __del__ was safe. In return, python would guarantee to actually do it, even if garbage collection is turned off. -jJ
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4