Python: Global Object Destruction

python

Solution

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.

Problem

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.

Original source

Related problems