I have a global instance, which I expect to be destroyed (function __del__ called) when the Python interpreter exits. Am I expecting too much of the Python interpreter?
My method of testing this is to put a print in the __del__ function, run python.exe from a command line, and then pressing Ctrl/Break. At this point, I would expect to see the print in the command-line window. However, I do not.
Yes, you're expecting too much. Python doesn't make any guarantees about calling __del__:
It is not guaranteed that
__del__()methods are called for objects that still exist when the interpreter exits.
Edit:
Generally, you should avoid using __del__. For most cases context managers are better. For the rare case when you need to make sure that some external (i.e. allocated from C code) resource gets cleaned up when the interpreter exits you can use the atexit module.
You could add a handler for the signal.SIGBREAK signal. That would let you intercept ctrl + break. Form the documentation:
import signal, os
def handler(signum, frame):
print 'Someone is trying to exit!', signum
signal.signal(signal.SIGBREAK, handler)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With