Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python destructor not called

Tags:

python

Anyone has any idea how to get my destructor called on object destruction?

def __del__(self):
    os.unlink(self.pidfile)

Scenario: There is a Daemon that runs Process. Daemon gets a SIGTERM, and immediately sends a SIGTERM to Process. Process stops execution without __del__ called.

like image 204
Rápli András Avatar asked Oct 18 '22 22:10

Rápli András


1 Answers

As referenced in the comments, defining an __exit__ method for your object and using the with statement is the preferred way of "destructing" objects. It's more explicit and predictable.

However, even using the with statement won't guarantee clean destruction of your object if a SIGTERM is received. In order to do something when a signal is received, you'll have to add a signal handler.

import signal
import sys

def handle_signal(signum, frame):
    print('Got signal')
    #  Do some cleanup
    sys.exit(signum)  # Maybe ???

signal.signal(signal.SIGTERM, handle_signal)

At this point, you might consider calling del your_object in the signal handler, but even that is not guaranteed to call the __del__ method if there are still references to that object in the program (see the docs for __del__)

So bottom line I think is not to expect things to go absolutely smoothly and predictably if you're depending on SIGTERM to close your Python programs.

like image 76
Billy Avatar answered Nov 15 '22 06:11

Billy