Singleton Design Pattern
import sqlite3 class Singleton: __instance = None __db = None __conn = None @staticmethod def getInstance(): if Singleton.__instance == None: Singleton() return Singleton.__instance def getConnection(self): return self.__conn def __init__(self, db = None): if Singleton.__instance != None: raise Exception("instance already exists, use getInstance method") else: Singleton.__instance = self Singleton.__db = db Singleton.__conn = conn1 = sqlite3.connect(db) def __str__(self): return "connection object for "+self.__db s = Singleton(db="mydb.sql") print(s) #this will fail #s = Singleton(db="anotherdb.sql") s = Singleton.getInstance() print(s) conn = Singleton.getInstance().getConnection() print(conn) conn = Singleton.getInstance().getConnection() print(conn)