forked from Tribler/dispersy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsingleton.py
294 lines (237 loc) · 9.42 KB
/
singleton.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# Python 2.5 features
from __future__ import with_statement
"""
Helper class to easily and cleanly use singleton objects
"""
from gc import get_referrers
from random import sample
from threading import RLock
# update version information directly from SVN
from .revision import update_revision_information
update_revision_information("$HeadURL$", "$Revision$")
def cleanup():
"""
Removes all singleton instances from existing Singleton subclasses
"""
def clear(cls):
if hasattr(cls, "_singleton_instance"):
delattr(cls, "_singleton_instance")
if hasattr(cls, "_singleton_instances"):
delattr(cls, "_singleton_instances")
for subcls in cls.__subclasses__():
clear(subcls)
clear(Singleton)
clear(Parameterized1Singleton)
class Singleton(object):
"""
Usage:
class Foo(Singleton):
def __init__(self, bar):
self.bar = bar
# create singleton instance and set bar = 123
foo = Foo.get_instance(123)
assert foo.bar == 123
# retrieve existing singleton instance, Foo.__init__ is NOT called again
foo = Foo.get_instance()
assert foo.bar == 123
# retrieve existing singleton instance, bar is NOT set to 456
foo = Foo.get_instance(456)
assert foo.bar == 123
"""
_singleton_lock = RLock()
@classmethod
def has_instance(cls, singleton_placeholder=None):
"""
Returns the existing singleton instance or None
"""
if singleton_placeholder is None:
singleton_placeholder = cls
with singleton_placeholder._singleton_lock:
if hasattr(singleton_placeholder, "_singleton_instance"):
return getattr(singleton_placeholder, "_singleton_instance")
@classmethod
def get_instance(cls, *args, **kargs):
"""
Returns the existing singleton instance or create one
"""
if "singleton_placeholder" in kargs:
singleton_placeholder = kargs.pop("singleton_placeholder")
else:
singleton_placeholder = cls
with singleton_placeholder._singleton_lock:
if not hasattr(singleton_placeholder, "_singleton_instance"):
setattr(singleton_placeholder, "_singleton_instance", cls(*args, **kargs))
return getattr(singleton_placeholder, "_singleton_instance")
@classmethod
def del_instance(cls, singleton_placeholder=None):
"""
Removes the existing singleton instance
"""
if singleton_placeholder is None:
singleton_placeholder = cls
with singleton_placeholder._singleton_lock:
if hasattr(singleton_placeholder, "_singleton_instance"):
delattr(singleton_placeholder, "_singleton_instance")
@classmethod
def referenced_instance(cls, singleton_placeholder=None):
"""
Returns True if this singleton instance is referenced.
Warning: this method uses the GC.get_referrers to determine the number of references. This
method is very expensive to use!
"""
if singleton_placeholder is None:
singleton_placeholder = cls
with singleton_placeholder._singleton_lock:
if hasattr(singleton_placeholder, "_singleton_instance"):
return len(get_referrers(getattr(cls, "_singleton_instance"))) > 1
return False
class Parameterized1Singleton(object):
"""
The required first parameter is used to uniquely identify a
singleton instance. Only one instance per first parameter will be
created.
class Bar(Parameterized1Singleton):
def __init(self, name):
self.name = name
a1 = Bar.get_instance('a', 'a')
a2 = Bar.get_instance('a', *whatever)
b1 = Bar.get_instance('b', 'b')
assert a1 == a2
assert a1 != b1
assert a2 != b2
"""
_singleton_lock = RLock()
@classmethod
def has_instance(cls, arg):
"""
Returns the existing singleton instance or None
"""
assert hasattr(arg, "__hash__")
with cls._singleton_lock:
if hasattr(cls, "_singleton_instances") and arg in getattr(cls, "_singleton_instances"):
return getattr(cls, "_singleton_instances")[arg]
@classmethod
def get_instance(cls, *args, **kargs):
"""
Returns the existing singleton instance or create one
"""
assert len(args) > 0
assert hasattr(args[0], "__hash__")
with cls._singleton_lock:
if not hasattr(cls, "_singleton_instances"):
setattr(cls, "_singleton_instances", {})
if not args[0] in getattr(cls, "_singleton_instances"):
getattr(cls, "_singleton_instances")[args[0]] = cls(*args, **kargs)
return getattr(cls, "_singleton_instances")[args[0]]
@classmethod
def del_instance(cls, arg):
"""
Removes the existing singleton instance
"""
assert hasattr(arg, "__hash__")
with cls._singleton_lock:
if hasattr(cls, "_singleton_instances") and arg in getattr(cls, "_singleton_instances"):
del getattr(cls, "_singleton_instances")[arg]
if not getattr(cls, "_singleton_instances"):
delattr(cls, "_singleton_instances")
@classmethod
def get_instances(cls):
"""
Returns a list with all the singleton instances.
"""
with cls._singleton_lock:
if hasattr(cls, "_singleton_instances"):
return getattr(cls, "_singleton_instances").values()
else:
return []
@classmethod
def referenced_instance(cls, arg):
"""
Returns True if this singleton instance is referenced.
Warning: this method uses the GC.get_referrers to determine the number of references. This
method is very expensive to use!
"""
assert hasattr(arg, "__hash__")
with cls._singleton_lock:
if hasattr(cls, "_singleton_instances") and arg in getattr(cls, "_singleton_instances"):
return len(get_referrers(getattr(cls, "_singleton_instances")[arg])) > 1
return False
@classmethod
def reference_instances(cls):
"""
Returns a list with (reference-count, instance) tuples.
Warning: this method uses the GC.get_referrers to determine the number of references. This
method is very expensive to use!
"""
with cls._singleton_lock:
if hasattr(cls, "_singleton_instances"):
return [(len(get_referrers(instance)) - 2, instance) for instance in getattr(cls, "_singleton_instances").itervalues()]
return []
@classmethod
def sample_reference_instances(cls, size):
"""
Returns a list with at most SIZE randomly chosen (reference-count, instance) tuples.
Warning: this method uses the GC.get_referrers to determine the number of references. This
method is very expensive to use!
"""
assert isinstance(size, int)
assert 0 < size
with cls._singleton_lock:
if hasattr(cls, "_singleton_instances"):
instances = getattr(cls, "_singleton_instances")
if len(instances) < size:
# sample larger than population
return [(len(get_referrers(instance)) - 2, instance) for instance in instances.itervalues()]
else:
return [(len(get_referrers(instance)) - 2, instance) for instance in (instances[arg] for arg in sample(instances, size))]
return []
if __name__ == "__main__":
from .dprint import dprint
def assert_(value, *args):
if not value:
raise AssertionError(*args)
class Foo(Singleton):
def __init__(self, message):
self.message = message
assert_(not Foo.referenced_instance())
foo = Foo.get_instance("foo")
assert_(foo.message == "foo")
assert_(foo.referenced_instance())
del foo
foo = Foo.get_instance("bar")
assert_(foo.message == "foo")
assert_(foo.referenced_instance())
del foo
assert_(not Foo.referenced_instance())
Foo.del_instance()
assert_(not Foo.referenced_instance())
#
#
#
class Foo(Parameterized1Singleton):
def __init__(self, key, message):
self.message = message
def __eq__(self, other):
return id(self) == id(other) if isinstance(other, Foo) else self.message == other
assert_(not Foo.referenced_instance(1))
assert_(Foo.reference_instances() == [])
assert_(Foo.sample_reference_instances(10) == [])
Foo.get_instance(1, "foo")
assert_(Foo.reference_instances() == [(0, "foo")])
assert_(Foo.sample_reference_instances(10) == [(0, "foo")])
foo = Foo.get_instance(1, "foo")
assert_(foo.message == "foo")
assert_(foo.referenced_instance(1))
assert_(Foo.reference_instances() == [(1, "foo")])
assert_(Foo.sample_reference_instances(10) == [(1, "foo")])
foo = Foo.get_instance(1, "bar")
assert_(foo.message == "foo")
assert_(foo.referenced_instance(1))
del foo
assert_(not Foo.referenced_instance(1))
assert_(Foo.reference_instances() == [(0, "foo")])
assert_(Foo.sample_reference_instances(10) == [(0, "foo")])
Foo.del_instance(1)
assert_(not Foo.referenced_instance(1))
assert_(Foo.reference_instances() == [])
assert_(Foo.sample_reference_instances(10) == [])