Package SloppyCell :: Module KeyedList_mod
[hide private]

Source Code for Module SloppyCell.KeyedList_mod

  1  """ 
  2  Holds the KeyedList class. 
  3  """ 
  4  import copy 
  5  import os 
  6   
7 -class KeyedList(list):
8 - def __init__(self, arg1 = None):
9 # We stored both a dictionary mapping keys to indices and a list of 10 # keys for efficiency 11 self.keyToIndex = {} 12 self.storedKeys = [] 13 14 if hasattr(arg1, 'items'): 15 items = arg1.items() 16 else: 17 items = arg1 18 19 if items is not None: 20 for (key, value) in items: 21 self.set(key, value)
22
23 - def copy(self):
24 return copy.copy(self)
25
26 - def deepcopy(self):
27 return copy.deepcopy(self)
28
29 - def set_order(self, order):
30 if len(order) != len(self): 31 raise ValueError, 'New order is of a different length!' 32 33 oldOrder = copy.copy(self.keyToIndex) 34 oldValues = copy.copy(self.values()) 35 self.storedKeys = [] 36 for (index, key) in enumerate(order): 37 self.keyToIndex[key] = index 38 self.storedKeys.append(key) 39 self[index] = oldValues[oldOrder[key]]
40 41 setOrder = set_order 42
43 - def reverse(self):
44 self.set_order(self.keys()[::-1])
45
46 - def del_by_key(self, key):
47 index = self.index_by_key(key) 48 del self[index]
49
50 - def __delitem__(self, index):
51 list.__delitem__(self, index) 52 del self.storedKeys[index] 53 for key, ii in self.keyToIndex.items(): 54 if ii > index: 55 self.keyToIndex[key] -= 1 56 elif ii == index: 57 del self.keyToIndex[key]
58
59 - def __delslice__(self, start, stop):
60 # XXX: Not sure of behavior here 61 if stop > len(self): 62 stop = len(self) 63 64 for index in range(start, stop)[::-1]: 65 del self[index]
66
67 - def __copy__(self):
68 instance = self.__new__(self.__class__) 69 instance.__init__(self.items()) 70 return instance
71
72 - def __deepcopy__(self, memo):
73 # XXX: Not handling recursion here 74 instance = self.__new__(self.__class__) 75 instance.__init__(copy.deepcopy(self.items())) 76 return instance
77 78 # 79 # Methods for manipulating by key. 80 #
81 - def set(self, key, value):
82 try: 83 self[self.keyToIndex[key]] = value 84 except KeyError: 85 list.append(self, value) 86 self.storedKeys.append(key) 87 self.keyToIndex[key] = len(self)-1
88
89 - def index_by_key(self, key):
90 return self.keyToIndex[key]
91
92 - def remove_by_key(self, key):
93 del self[self.keyToIndex[key]]
94
95 - def get(self, key, default = None):
96 try: 97 return self[self.keyToIndex[key]] 98 except KeyError: 99 return default
100 101 setByKey = set 102 getByKey = get 103 indexByKey = index_by_key 104 removeByKey = remove_by_key 105
106 - def keys(self):
107 return copy.copy(self.storedKeys)
108
109 - def update(self, other):
110 if isinstance(other, dict) or isinstance(other, KeyedList): 111 for key, value in other.items(): 112 self.set(key, value) 113 else: 114 if(len(self) != len(other)): 115 raise ValueError, 'Other list not of same length!' 116 for ii in range(len(self)): 117 self[ii] = other[ii]
118
119 - def has_key(self, key):
120 return self.keyToIndex.has_key(key)
121
122 - def setdefault(self, key, default=None):
123 if not self.keyToIndex.has_key(key): 124 self.set(key, default)
125
126 - def values(self):
127 return self[:]
128
129 - def items(self):
130 return zip(self.keys(), self.values())
131
132 - def __repr__(self):
133 return 'KeyedList(%s)' % repr(self.items())
134
135 - def __str__(self):
136 return os.linesep.join(['['] + 137 [str(tup) + ',' for tup in self.items()] + [']'])
138 139 # 140 # list methods not supported 141 #
142 - def __add__(self, other):
143 new_kl = self.copy() 144 new_kl += other 145 return new_kl
146
147 - def __iadd__(self, other):
148 if not isinstance(other, self.__class__): 149 raise TypeError('Can only add another KeyedList to a KeyedList') 150 for k,v in other.items(): 151 if not self.has_key(k): 152 self.set(k, v) 153 else: 154 raise ValueError('Addition would result in duplicated keys.') 155 return self
156
157 - def extend(self, other):
158 self += other
159
160 - def __imul__(self, factor):
161 raise NotImplementedError
162 - def __mul__(self, factor):
163 raise NotImplementedError
164 - def __rmul__(self, factor):
165 raise NotImplementedError
166
167 - def append(self, object):
168 raise NotImplementedError
169
170 - def insert(self, index, object):
171 raise NotImplementedError
172
173 - def insert_item(self, index, key, value):
174 if self.has_key(key): 175 raise ValueError('Insertion would result in duplicated key: %s.' 176 % str(key)) 177 list.insert(self, index, value) 178 self.storedKeys.insert(index, key) 179 for k, ii in self.keyToIndex.items(): 180 if ii > index: 181 self.keyToIndex[k] += 1 182 self.keyToIndex[key] = index
183
184 - def pop_value(self, index=-1):
185 val = self[index] 186 del self[index] 187 return val
188 pop = pop_value 189
190 - def pop_key(self, index=-1):
191 key = self.storedKeys[index] 192 del self[index] 193 return key
194
195 - def pop_item(self, index=-1):
196 item = (self.storedKeys[index], self[index]) 197 del self[index] 198 return key
199
200 - def remove_by_value(self, other):
201 index = self.index(other) 202 del self[index]
203 remove = remove_by_value 204
205 - def sort_by_key(self):
206 """ 207 Sort based on key of each entry 208 """ 209 keys = self.keys() 210 keys.sort() 211 self.set_order(keys)
212
213 - def sort_by_value(self):
214 """ 215 Sort based on value of each entry 216 """ 217 decorated = zip(self.values(), self.keys()) 218 decorated.sort() 219 sorted_keys = [k for (v,k) in decorated] 220 self.set_order(sorted_keys)
221 sort = sort_by_value
222