singleton or Borg?

Rajarshi Guha rajarshi at
Mon Sep 15 00:00:48 CEST 2003

Hi, I'm having a little problem with understanding the working of a
singleton and borg class. Basically I nedd an class whose state will be
shared across several modules. I found the stuff on the ASPN cookbook but
it does'nt seem to be working for me. I've included some code:
class Borg:
    __shared_state = {}
    def __init__(self):
        self.__dict__ = self.__shared_state
        self.val = {}
class Singleton(object):
    def __new__(type):
        if not '_the_instance' in type.__dict__:
            type._the_instance = object.__new__(type)
        return type._the_instance    
class Tester(Singleton):    
    def __init__(self):
        self.val = {}
import Borg,v

x = Borg.Tester()
x.val['a'] = 1

print x.val
print x.val
import Borg

def func():
    y = Borg.Tester()
    print y.val, '...from'
    y.val['a'] = 2

I had expected to see:
{'a':1} ...from

However I get
{} ...from

Should'nt the instantiation of val in v.func() just use the val that was
already created when it was instatntiated in

I just cant seem to wrap my head around this oen, so any suggestions
would be appreciated.


More information about the Python-list mailing list