Singletons using metaclasses

suggest change

A 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):
        try:
            return cls.__instance
        except AttributeError:
            cls.__instance = super(SingletonType, cls).__call__(*args, **kwargs)
            return cls.__instance
class MySingleton(object):
    __metaclass__ = SingletonType

In Python 3:

class MySingleton(metaclass=SingletonType):
    pass
MySingleton() is MySingleton()  # True, only one instantiation occurs

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents