How is the below decorator make Database a singleton?
The way I am understanding it is that the @singleton decorator makes the Database class to a function that returns a Database object. However, since it's now acting like a function, when the function call ends, function variables should be dead (e.g. instances variable).
The weird part is that when I call this function the second time, it seems like the instance variable is still alive and store the previous information, even id is the same. How is this happening? Can someone please help me understand this?
Thank you in advance
def singleton(cls):
instances = {}
def get_instance(*args, **kwargs):
nonlocal instances
print(instances, id(instances))
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class Database:
def __init__(self):
print('Loading database')
if __name__ == '__main__':
db1 = Database() # first call.
db2 = Database() # second call. why is this returning the same id?
Output
{} 4011784
Loading database
{<class '__main__.Database'>: <__main__.Database object at 0x0577C148>} 4011784