Singletons using metaclasses
suggest changeA singleton is a pattern that restricts the instantiation of a class to one instance/object. For more info on python singleton design patterns, see here.
class SingletonType(type):
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
class MySingleton(metaclass=SingletonType):
pass
MySingleton() is MySingleton() # True, only one instantiation occurs
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents