python singleton

May 11, 2012   coding

A version of python singleton pattern, it is not very pretty and breaks a bunch of pep 20, but in some cases is useful.

Singleton Pattern

class Singleton(object):
    __instance = {}

    def __new__(cls, *args, **kwargs):
        if cls.__name__ not in cls.__instance:
            cls.__instance[cls.__name__] = super(cls.__class__, cls).__new__(cls, *args, **kwargs)
            setattr(cls.__instance[cls.__name__], '__init', True)
            setattr(cls.__instance[cls.__name__], '__init', False)
        return cls.__instance[cls.__name__]

    def __init__(self, *args, **kwargs):
        if getattr(self, '__init', False):
            # do initialization here

Alternatively consider the Borg Pattern below.

Borg Pattern

class Borg(object):
    __state = {}

    def __init__(self):
        self.__dict__ = self.__state
        if 'my_data' not in self.__dict__:
            # do initialization here, i.e.:
            self.my_data = 'initialize your data'