Singleton class using Metaclass
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]Using this singleton metaclass
class Singleton(metaclass=SingletonMeta):
pass
a = Singleton()
b = Singleton()
a is b # trueExplanation
SingletonMetawhen used as metaclass forSingleton,Singletonbecomes the class returned bySingletonMeta.- Calling
Singletoncalls__call__ofSingletonMetawhere we check ifSingletonclass is present in the dictionary. If it is not present, call__call__ofsuperwhich istype. type’s__call__creates the instance of classSingletonand gets stored in the dictionary.- next time when
Singletonis initialised again, the check happens and class is present and the instance gets returned.