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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
|
# util.py
# Copyright (C) 2005 Michael Bayer mike_mp@zzzcomputing.com
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
__all__ = ['OrderedProperties', 'OrderedDict']
import thread, weakref, UserList,string, inspect
def to_list(x):
if x is None:
return None
if not isinstance(x, list) and not isinstance(x, tuple):
return [x]
else:
return x
class OrderedProperties(object):
"""an object that maintains the order in which attributes are set upon it.
also provides an iterator and a very basic dictionary interface to those attributes.
"""
def __init__(self):
self.__dict__['_list'] = []
def keys(self):
return self._list
def get(self, key, default):
return getattr(self, key, default)
def has_key(self, key):
return hasattr(self, key)
def __iter__(self):
return iter([self[x] for x in self._list])
def __setitem__(self, key, object):
setattr(self, key, object)
def __getitem__(self, key):
try:
return getattr(self, key)
except AttributeError:
raise KeyError(key)
def __delitem__(self, key):
delattr(self, key)
del self._list[self._list.index(key)]
def __setattr__(self, key, object):
if not hasattr(self, key):
self._list.append(key)
self.__dict__[key] = object
class OrderedDict(dict):
"""A Dictionary that keeps its own internal ordering"""
def __init__(self, values = None):
self.list = []
if values is not None:
for val in values:
self.update(val)
def keys(self):
return self.list
def clear(self):
self.list = []
dict.clear(self)
def update(self, dict):
for key in dict.keys():
self.__setitem__(key, dict[key])
def setdefault(self, key, value):
if not self.has_key(key):
self.__setitem__(key, value)
return value
else:
return self.__getitem__(key)
def values(self):
return map(lambda key: self[key], self.list)
def __iter__(self):
return iter(self.list)
def itervalues(self):
return iter([self[key] for key in self.list])
def iterkeys(self):return self.__iter__()
def iteritems(self):
return iter([(key, self[key]) for key in self.keys()])
def __delitem__(self, key):
try:
del self.list[self.list.index(key)]
except ValueError:
raise KeyError(key)
dict.__delitem__(self, key)
def __setitem__(self, key, object):
if not self.has_key(key):
self.list.append(key)
dict.__setitem__(self, key, object)
def __getitem__(self, key):
return dict.__getitem__(self, key)
class ThreadLocal(object):
"""an object in which attribute access occurs only within the context of the current thread"""
def __init__(self, raiseerror = True):
self.__dict__['_tdict'] = {}
self.__dict__['_raiseerror'] = raiseerror
def __getattr__(self, key):
try:
return self._tdict["%d_%s" % (thread.get_ident(), key)]
except KeyError:
if self._raiseerror:
raise AttributeError(key)
else:
return None
def __setattr__(self, key, value):
self._tdict["%d_%s" % (thread.get_ident(), key)] = value
class HashSet(object):
"""implements a Set."""
def __init__(self, iter = None, ordered = False):
if ordered:
self.map = OrderedDict()
else:
self.map = {}
if iter is not None:
for i in iter:
self.append(i)
def __iter__(self):
return iter(self.map.values())
def contains(self, item):
return self.map.has_key(item)
def clear(self):
self.map.clear()
def append(self, item):
self.map[item] = item
def __add__(self, other):
return HashSet(self.map.values() + [i for i in other])
def __len__(self):
return len(self.map)
def __delitem__(self, key):
del self.map[key]
def __getitem__(self, key):
return self.map[key]
class HistoryArraySet(UserList.UserList):
"""extends a UserList to provide unique-set functionality as well as history-aware
functionality, including information about what list elements were modified
and commit/rollback capability. When a HistoryArraySet is created with or
without initial data, it is in a "committed" state. as soon as changes are made
to the list via the normal list-based access, it tracks "added" and "deleted" items,
which remain until the history is committed or rolled back."""
def __init__(self, data = None, readonly=False):
# stores the array's items as keys, and a value of True, False or None indicating
# added, deleted, or unchanged for that item
self.records = OrderedDict()
if data is not None:
self.data = data
for item in data:
# add items without triggering any change events
# *ASSUME* the list is unique already. might want to change this.
self.records[item] = None
else:
self.data = []
self.readonly=readonly
def __getattr__(self, attr):
"""proxies unknown HistoryArraySet methods and attributes to the underlying
data array. this allows custom list classes to be used."""
return getattr(self.data, attr)
def set_data(self, data):
"""sets the data for this HistoryArraySet to be that of the given data.
duplicates in the incoming list will be removed."""
# first mark everything current as "deleted"
for i in self.data:
self.records[i] = False
# switch array
self.data = data
# TODO: fix this up, remove items from array while iterating
for i in range(0, len(self.data)):
if not self._setrecord(self.data[i]):
del self.data[i]
i -= 1
def history_contains(self, obj):
"""returns true if the given object exists within the history
for this HistoryArrayList."""
return self.records.has_key(obj)
def __hash__(self):
return id(self)
def _setrecord(self, item):
if self.readonly:
raise "This list is read only"
try:
val = self.records[item]
if val is True or val is None:
return False
else:
self.records[item] = None
return True
except KeyError:
self.records[item] = True
return True
def _delrecord(self, item):
if self.readonly:
raise "This list is read only"
try:
val = self.records[item]
if val is None:
self.records[item] = False
return True
elif val is True:
del self.records[item]
return True
return False
except KeyError:
return False
def commit(self):
"""commits the added values in this list to be the new "unchanged" values.
values that have been marked as deleted are removed from the history."""
for key in self.records.keys():
value = self.records[key]
if value is False:
del self.records[key]
else:
self.records[key] = None
def rollback(self):
"""rolls back changes to this list to the last "committed" state."""
# TODO: speed this up
list = []
for key, status in self.records.iteritems():
if status is False or status is None:
list.append(key)
self.data[:] = []
self.records = {}
for l in list:
self.append_nohistory(l)
def added_items(self):
"""returns a list of items that have been added since the last "committed" state."""
return [key for key in self.data if self.records[key] is True]
def deleted_items(self):
"""returns a list of items that have been deleted since the last "committed" state."""
return [key for key, value in self.records.iteritems() if value is False]
def unchanged_items(self):
"""returns a list of items that have not been changed since the last "committed" state."""
return [key for key in self.data if self.records[key] is None]
def append_nohistory(self, item):
"""appends an item to the list without affecting the "history"."""
if not self.records.has_key(item):
self.records[item] = None
self.data.append(item)
def remove_nohistory(self, item):
"""removes an item from the list without affecting the "history"."""
if self.records.has_key(item):
del self.records[item]
self.data.remove(item)
def has_item(self, item):
return self.records.has_key(item)
def __setitem__(self, i, item):
if self._setrecord(a):
self.data[i] = item
def __delitem__(self, i):
self._delrecord(self.data[i])
del self.data[i]
def __setslice__(self, i, j, other):
i = max(i, 0); j = max(j, 0)
if isinstance(other, UserList.UserList):
l = other.data
elif isinstance(other, type(self.data)):
l = other
else:
l = list(other)
g = [a for a in l if self._setrecord(a)]
self.data[i:] = g
def __delslice__(self, i, j):
i = max(i, 0); j = max(j, 0)
for a in self.data[i:j]:
self._delrecord(a)
del self.data[i:j]
def append(self, item):
if self._setrecord(item):
self.data.append(item)
def insert(self, i, item):
if self._setrecord(item):
self.data.insert(i, item)
def pop(self, i=-1):
item = self.data[i]
if self._delrecord(item):
return self.data.pop(i)
def remove(self, item):
if self._delrecord(item):
self.data.remove(item)
def __add__(self, other):
raise NotImplementedError()
def __radd__(self, other):
raise NotImplementedError()
def __iadd__(self, other):
raise NotImplementedError()
class ScopedRegistry(object):
"""a Registry that can store one or multiple instances of a single class
on a per-application or per-thread scoped basis"""
def __init__(self, createfunc, defaultscope):
self.createfunc = createfunc
self.defaultscope = defaultscope
self.application = createfunc()
self.threadlocal = {}
self.scopes = {
'application' : {'call' : self._call_application, 'clear' : self._clear_application, 'set':self._set_application},
'thread' : {'call' : self._call_thread, 'clear':self._clear_thread, 'set':self._set_thread}
}
def __call__(self, scope = None):
if scope is None:
scope = self.defaultscope
return self.scopes[scope]['call']()
def set(self, obj, scope = None):
if scope is None:
scope = self.defaultscope
return self.scopes[scope]['set'](obj)
def clear(self, scope = None):
if scope is None:
scope = self.defaultscope
return self.scopes[scope]['clear']()
def _set_thread(self, obj):
self.threadlocal[thread.get_ident()] = obj
def _call_thread(self):
try:
return self.threadlocal[thread.get_ident()]
except KeyError:
return self.threadlocal.setdefault(thread.get_ident(), self.createfunc())
def _clear_thread(self):
try:
del self.threadlocal[thread.get_ident()]
except KeyError:
pass
def _set_application(self, obj):
self.application = obj
def _call_application(self):
return self.application
def _clear_application(self):
self.application = createfunc()
def constructor_args(instance, **kwargs):
classobj = instance.__class__
argspec = inspect.getargspec(classobj.__init__.im_func)
argnames = argspec[0] or []
defaultvalues = argspec[3] or []
(requiredargs, namedargs) = (
argnames[0:len(argnames) - len(defaultvalues)],
argnames[len(argnames) - len(defaultvalues):]
)
newparams = {}
for arg in requiredargs:
if arg == 'self':
continue
elif kwargs.has_key(arg):
newparams[arg] = kwargs[arg]
else:
newparams[arg] = getattr(instance, arg)
for arg in namedargs:
if kwargs.has_key(arg):
newparams[arg] = kwargs[arg]
else:
if hasattr(instance, arg):
newparams[arg] = getattr(instance, arg)
else:
raise "instance has no attribute '%s'" % arg
return newparams
|