title: Manage database connection with Python singletons
body: <p>I have created my own module to manage objects in database. In order to limit the connections to the database, I design a dedicated class in a singleton way.</p>
  
  <p>The construstor is invoked as expected but the destructor is never invoked so the database connection is never close.</p>
  
  <pre><code>class DBConnection:
      instance = None
      con = None
  
      def __new__(cls):
      if DBConnection.instance is None:
          DBConnection.instance = object.__new__(cls)
      return DBConnection.instance
  
      def __init__(self):
      if DBConnection.con is None:
          try:
              DBConnection.con = psycopg2.connect(database='...', user='...', password='...')
              print('Database connection opened.')
          except psycopg2.DatabaseError as db_error:
              print("Erreur :\n{0}".format(db_error))
  
      def __del__(self):
      if DBConnection.con is not None:
          DBConnection.close()
          print('Database connection closed.')
  </code></pre>
  
  <p>The first instance printed "Database connection opened." as expected. The second instance printed nothing as expected. The first instance deleted printed nothing as expected. The second instance deleted printed nothing but I was expected the message "Database connection closed".</p>
  
  <p>I easily understand the reason: a reference still exists, but I don't know why. How can I delete all the references in order to close the database connection?</p>
  
  <p>Regards,
  Serge</p>