I needed a singleton database class in a Python 2.7 program and wrote it this way.
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Database():
__metaclass__ = Singleton
def __init__(self):
self.db = MySQLdb.connect(...)
I like this pattern but I realized that this is even more elegant:
class Database():
db = MySQLdb.connect(...)
def __init__(self):
pass
It works because I do not really need the whole Database class to be a singleton. All I really want is a single database connection.
