Duncan Booth duncan.booth at invalid.invalid
Tue Apr 8 10:00:22 CEST 2008

Gabriel Rossetti <gabriel.rossetti at> wrote:

> we are writing an application that needs some cleanup to be done if
> the application is quit, normally (normal termination) or by a signal
> like SIGINT or SIGTERM. I know that the __del__ method exists, but
> unless I'm mistaken there is no guarantee as of when it will be
> called, and some objects may have already been released (at lease I've
> had trouble in the past accessing certain objects from inside __del__,
> probably since the parent class's __del__ has to be called first, then
> it's objects are already released by the time I need to do something
> with them). Another method would be to implement something using the
> signal module and have a callback that does all the cleanup when the
> app. is quit/terminated/interrupted and have all the child classes
> override that with their cleanup code.

I know that, at least on Windows, the default handler for SIGTERM (which
can be triggered by Ctrl+Break) causes Python to exit instantly with no
cleanup whatsoever. If this is a possible scenario for your application
then you will have to ensure that you have a signal handler to catch
SIGTERM at the very least. 

Then if you install an Exception hook through sys.excepthook() you
should be able to catch most other abnormal terminations[*] and that
just leaves atexit for the normal termination. 

I'm not sure about 'have all the child classes override that with their
cleanup code'. Needing any cleanup code like this must be considered
unusual, having multiple classes each with their own cleanup sounds
suspiciously as though you may have the wrong approach. For example, if
you are trying to save some kind of state which has to be consistent
then using a transactional database may be a better approach. 

[*] except of course for things like power failure. You simply cannot
catch *all* terminations. 

More information about the Python-list mailing list