>> python singleton  (79 views)

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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)
        else:
            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
            pass

Alternatively consider the Borg Pattern below.

Borg Pattern

1
2
3
4
5
6
7
8
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'