Borg

So I was reading up on some Python and found this interesting pattern by Alex Martelli. It’s call the Borg pattern, which I think is very cool and a bit philosphical.

class Borg(object):
    _shared_data = {}
    def __init__(self):
        self.__dict__ = self._shared_data

class Singleton(Borg):
    def __init__(self, v):
        super(Singleton, self).__init__()
        self.value = v
    def __str__(self):
        return str(self.value)

# lets create some instances
>> one = Singelton("first")
>> print(one)
>> 'first'
>> two = Singelton("second")
>> print(two)
>> 'second'
>> print(one)
>> 'second'  # wow! thats cool ryt?!

What’s going on here?

All Singleton objects have the same share the same state - it is made possbile by the all powerful __dict__ attribute. It is a dictionary that contains all attributes and its values. We first assign __dict__ to refer to the dictionary refered to by _shared_data. This makes sure that every time an object for Singelton is created the __dict__ attribute of the Borg object is referring to the same instance variable _shared_data. Thus, when inheriting the class, the child class’s __dict__ is overwritten by parent class’s __dict__.

The end

As a closing note, about the philosphy of Borg, think about why we need a singleton? At least one of the reasons why we need one is to maintain a common state among different objects (some would say, that is the only reason). Borg does that for us, one state for all objects, for we are the Borg, we are all the same:)

The Borg pattern is so cool because it is so simple.