I am defining a Python singleton as follows:
class Database:
initialized = False
def __init__(self):
self.id = random.randint(1,101)
print("Generated an id of ", self.id)
print("Loading database from file")
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Database, cls)\
.__new__(cls, *args, **kwargs)
return cls._instance
This works in the sense that every single call to Database()
actually returns one and only instance. However, the __init__()
method is still called on every invocation. For example,
database = Database()
if __name__ == '__main__':
d1 = Database()
d2 = Database()
print(d1.id, d2.id)
print(d1 == d2)
print(database == d1)
Produces the output
Generated an id of 8
Loading database from file
Generated an id of 89
Loading database from file
Generated an id of 81
Loading database from file
81 81
True
True
Why is that? What can I do to avoid the initializer being called more than once?