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

  1. SingletonMeta when used as metaclass for Singleton, Singleton becomes the class returned by SingletonMeta.
  2. Calling Singleton calls __call__ of SingletonMeta where we check if Singleton class is present in the dictionary. If it is not present, call __call__ of super which is type.
  3. type’s __call__ creates the instance of class Singleton and gets stored in the dictionary.
  4. next time when Singleton is initialised again, the check happens and class is present and the instance gets returned.