1
0
Fork 0
mirror of synced 2024-12-22 14:11:07 -05:00

Improve Singleton metaclass

This commit is contained in:
Anish Athalye 2024-12-07 18:24:18 -05:00
parent 8d94c6ec1a
commit 4edfa82607

View file

@ -1,7 +1,9 @@
class Singleton(type): class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs): def __call__(cls, *args, **kwargs):
if cls not in cls._instances: if not hasattr(cls, "_singleton_instance"):
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) cls._singleton_instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls] return cls._singleton_instance
def reset_instance(cls):
if hasattr(cls, "_singleton_instance"):
del cls._singleton_instance