5 ms·
> Be careful, however, as there is no guarantee that __del__ will be executed if the object is still alive when the interpreter exits, so __del__ can't serve as
by saagarjha 8y ago
> Be careful, however, as there is no guarantee that __del__ will be executed if the object is still alive when the interpreter exits, so __del__ can't serve as a replacement for good coding practices (like always closing a connection when you're done with it.
When the interpreter exits, your program's resources should be reclaimed by the operating system, right? So why not just use __del__?
- cjhanks 8y agoSay it's a socket and you want to send some sort of "END_OF_STREAM" message before closing.
- gvx 8y agoYou almost always only want to implement __del__ if you're writing an extension in C. Otherwise, the GC generally takes care of cleanup perfectly fine. And in cases like the one cjhanks describes, __del__ doesn't get called reliably enough. In those cases, using a contextmanager is better.
- pfranz 8y agoThat wouldn't work if you expected __del__ to cleanup lock files or temp files or to manage other external resources.
- lstyls 8y agoIf this were the case, there would be no need for SIGTERM. The OS doesn't know the application logic and can't guarantee clean termination from the application's perspective. As others have said, there's rarely reason to override `__del__`, and when you do you know exactly why you need it.
- falsedan 8y agoThe python interpreter can choose not to call it. I've had to register essential cleanup with `atexit` instead.