Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Global Object Destruction [duplicate]

Tags:

python

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.

like image 506
barak manos Avatar asked Mar 17 '26 17:03

barak manos


2 Answers

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.

like image 68
lqc Avatar answered Mar 19 '26 06:03

lqc


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)
like image 36
Jason Sperske Avatar answered Mar 19 '26 05:03

Jason Sperske



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!