Singletons using metaclasses

Download python eBook

Example

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
Python 2.x2.7
class MySingleton(object):
    __metaclass__ = SingletonType
Python 3.x3.0
class MySingleton(metaclass=SingletonType):
    pass
MySingleton() is MySingleton()  # True, only one instantiation occurs

Stats

Contributors: 6
2016-11-06
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook