2

I have a python script which uses a MySQL database connection, I want the database connection to be closed when the instance of the class does no longer exist therefore in my class I implemented a disconnect method as follows:

def disconnect(self):
    '''Disconnect from the MySQL server'''
    if self.conn is not None:
        self.log.info('Closing connection')
        self.conn.close()
        self.conn = None
        self.curs = None

Now I was thinking of calling this method as follows:

def __del__(self):
    self.disconnect()

However I've read that you cannot assume that the __del__ method will ever be called, if that is the case, what is the correct way? Where / when should I call the disconnect() method?

Important sidenote is that my script is running as a unix daemon and is instantiated as follows:

if __name__ == '__main__':
    daemon = MyDaemon(PIDFILE)
    daemonizer.daemonizerCLI(daemon, 'mydaemon', sys.argv[0], sys.argv[1], PIDFILE)

The above takes the class MyDaemon and creates an Unix Daemon by executing a double fork.

1 Answer 1

2

Maybe you could use with statment and populate __exit__ method. For example:

class Foo(object):

  def disconnect(self):
    '''Disconnect from the MySQL server'''
    if self.conn is not None:
        self.log.info('Closing connection')
        self.conn.close()
        self.conn = None
        self.curs = None
        print "disconnect..."

  def __exit__(self, *err):
    self.disconnect()

if __name__ == '__main__':
  with Foo() as foo:
    print foo, foo.curs
Sign up to request clarification or add additional context in comments.

1 Comment

I think this could be indeed the solution, however I'm not sure if it works in my specific situation as I'm running my script as a Unix daemon, I've edited my question to include this aspect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.