pythonsingleton

Why is this Python Borg / Singleton pattern working


i just stumbled around the net and found these interesting code snipped:

http://code.activestate.com/recipes/66531/

class Borg:
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state
    # and whatever else you want in your class -- that's all!

I understand what a singleton is but i don't understand that particular code snipped. Could you explain me how/where "__shared_state" is even changed at all?

I tried it in ipython:

In [1]: class Borg:
   ...:         __shared_state = {}
   ...:     def __init__(self):
   ...:             self.__dict__ = self.__shared_state
   ...:     # and whatever else you want in your class -- that's all!
   ...: 
In [2]: b1 = Borg()
In [3]: b2 = Borg()
In [4]: b1.foo="123"
In [5]: b2.foo
Out[5]: '123'
In [6]: 

but cannot fully understand how this could happen.


Solution

  • Because the class's instance's __dict__ is set equal to the __share_state dict. They point to the same object. (Classname.__dict__ holds all of the class attributes)

    When you do:

    b1.foo = "123"
    

    You're modifying the dict that both b1.__dict__ and Borg.__shared_state refer to.