Reputation: 3340
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.
Upvotes: 2
Views: 1067
Reputation: 750
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
Upvotes: 2