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 # true
Explanation
SingletonMeta
when used as metaclass forSingleton
,Singleton
becomes the class returned bySingletonMeta
.- Calling
Singleton
calls__call__
ofSingletonMeta
where we check ifSingleton
class is present in the dictionary. If it is not present, call__call__
ofsuper
which istype
. type
’s__call__
creates the instance of classSingleton
and gets stored in the dictionary.- next time when
Singleton
is initialised again, the check happens and class is present and the instance gets returned.