5
This class makes a thread local Singleton
6
(i.e. every threads sees a differnt singleton)
7
It also makes a different singleton for each derived class.
8
The objects behave like dictionaries and attributes/values
9
are mapped into keys/values.
10
But, while if not 'x' in a, a['x'] raises and exception a.x returns None
15
>>> b=Singleton() # same singleton as a
18
>>> class C(Singleton): pass
19
>>> c=C() # new singleton
21
>>> d=C() # same singleton as c
24
>>> d.set_state({}) # state can be reset
28
thread = threading.local()
30
if not hasattr(Singleton.thread,str(self.__class__)):
31
setattr(Singleton.thread,str(self.__class__),{})
32
def __getitem__(self,key):
33
return getattr(Singleton.thread,str(self.__class__))[key]
34
def __setitem__(self,key,value):
35
getattr(Singleton.thread,str(self.__class__))[key]=value
36
def __setattr__(self,key,value):
37
getattr(Singleton.thread,str(self.__class__))[key]=value
38
def __delattr__(self,key):
39
del getattr(Singleton.thread,str(self.__class__))[key]
40
def get(self,key,value):
41
return getattr(Singleton.thread,str(self.__class__)).get(key,value)
42
def __getattr__(self,key):
43
return getattr(Singleton.thread,str(self.__class__)).get(key,None)
45
return '<Storage ' + repr(getattr(Singleton.thread,str(self.__class__))) + '>'
47
return str(getattr(Singleton.thread,str(self.__class__)))
48
def __getstate__(self):
49
return getattr(Singleton.thread,str(self.__class__))
50
def __setstate__(self, value):
51
setattr(Singleton.thread,str(self.__class__),value)
52
def __cmp__(self,other):
54
def __contains__(self,value):
55
return value in getattr(Singleton.thread,str(self.__class__))
57
return hash(getattr(Singleton.thread,str(self.__class__)))
59
return len(getattr(Singleton.thread,str(self.__class__)))
60
def has_key(self,key):
63
return getattr(Singleton.thread,str(self.__class__)).keys()
65
return getattr(Singleton.thread,str(self.__class__)).values()
67
return getattr(Singleton.thread,str(self.__class__)).items()
69
return getattr(Singleton.thread,str(self.__class__)).iterkeys()
71
return getattr(Singleton.thread,str(self.__class__)).itervalues()
73
return getattr(Singleton.thread,str(self.__class__)).iteritems()
74
def update(self,*a,**b):
75
return getattr(Singleton.thread,str(self.__class__)).update(*a,**b)
77
return getattr(Singleton.thread,str(self.__class__)).popitem()
79
return getattr(Singleton.thread,str(self.__class__)).clear()
81
return getattr(Singleton.thread,str(self.__class__)).copy()
83
return getattr(Singleton.thread,str(self.__class__)).__iter__()
85
return getattr(Singleton.thread,str(self.__class__))
86
def set_state(self,storage):
87
setattr(Singleton.thread,str(self.__class__),storage)
89
if __name__ == '__main__':