As answered brilliantly by agf here, a possible implementation of a Singleton in Python could be using this metaclass:
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
However, I do not understand the use of _instance
. I know it's a dict used to store instances indexed by their class. However, it is declared as a class attribute (_instances = {}
), and it is used as an attribute of cls
(if cls not in cls._instances:
). How can the two be the same?