/usr/share/pyshared/mx/Misc/OrderedMapping.py is in python-egenix-mxtools 3.2.1-1ubuntu1.
This file is owned by root:root, with mode 0o755.
The actual contents of the file can be viewed below.
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 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 | #! /usr/bin/python
""" OrderedMapping - A compromise between a dictionary and a list.
Copyright (c) 1998-2000, Marc-Andre Lemburg; mailto:mal@lemburg.com
See the documentation for further information on copyrights,
or contact the author. All Rights Reserved.
"""
import types, operator
from mx.Tools import freeze
import mx.Tools.NewBuiltins
class OrderedMapping:
""" OrderedMapping - A compromise between a dictionary and a list.
The object stores the keys in a list and a the items (key,value)
in a dictionary. Order in the dictionary is implied by the key
list. New dictionary keys are appended to the key list and thus
newer keys have higher order.
Note that you can manipulate the ordering with several methods.
Also, assignment, retrieval and deletion using the order integers
is possible.
The object differentiates between queries referring to order and
ones referring to keys by checking the query index's
type. Integers are interpreted as order index and all other types
as keys.
"""
def __init__(self, presets=None):
""" Create an OrderedMapping object.
presets may be given as list of tuples to initialize the
object with (key,value) pairs. The objects are inserted in
order given by in presets object.
"""
self.list = [] # list of keys
self.dict = {} # dict
# init
if presets is not None:
if hasattr(presets, 'items'):
items = presets.items()
else:
items = presets
self.additems(items)
def additems(self, items):
""" Adds the (key, value) pairs in items to the object
in the order they are specified.
"""
l = self.list
append = l.append
d = self.dict
has_key = d.has_key
for key, value in items:
if has_key(key):
raise ValueError,\
'more than one value for key %s' % repr(key)
append(key)
d[key] = value
def __repr__(self):
""" Returns a string representation of the object comparable to
to the dictionary built-in object.
"""
l = []
for key in self.list:
value = self.dict[key]
l.append(repr(key)+': '+repr(value))
return '{' + ', '.join(l) + '}'
def __cmp__(self, other):
""" Compares the object against another OrderedMapping object
or dictionary.
Ordering of the contents is important when comparing
OrderedMapping objects. It is not when comparing to
dictionaries.
"""
if isinstance(other,OrderedMapping):
return cmp((self.list,self.dict), (other.list,other.dict))
else:
return cmp(self.dict,other)
def __len__(self):
""" Returns the number of object stored.
"""
return len(self.list)
def __getitem__(self, keyindex,
IntType=types.IntType):
""" Returns the object at position keyindex.
keyindex may either be an integer to index an object by
position or an arbitrary key object which is then used for
dictionary like lookup.
"""
# runtime O(1)
if type(keyindex) is IntType:
# om[0]
return self.dict[self.list[keyindex]]
else:
# om['bar']
return self.dict[keyindex]
def __setitem__(self, keyindex, value,
IntType=types.IntType):
""" Sets the position keyindex to value.
keyindex may either be an integer to index an object by
position or an arbitrary key object which is then used for
dictionary like lookup.
In the latter case, if no key is found, value is appended
to the object.
"""
# runtime O(1)
if type(keyindex) is IntType:
# om[0] = 'foo': update value
self.dict[self.list[keyindex]] = value
else:
# om['bar'] = 'foo'
if self.dict.has_key(keyindex):
# update value
self.dict[keyindex] = value
else:
# append/add value
self.dict[keyindex] = value
self.list.append(keyindex)
def __delitem__(self, keyindex,
IntType=types.IntType):
""" Deletes the object at position keyindex.
keyindex may either be an integer to index an object by
position or an arbitrary key object which is then used for
dictionary like lookup.
"""
if type(keyindex) is IntType:
# del om[0]; runtime O(1)
key = self.list[keyindex]
del self.dict[key]
del self.list[keyindex]
else:
# del om['foo']; runtime O(n)
del self.dict[keyindex]
self.list.remove(keyindex)
def __getslice__(self, i, j):
""" Return the slice [i:j] of the object as OrderedMapping
instance.
"""
# om[1:3]; runtime O(j-i)
om = OrderedMapping()
om.list = keys = self.list[i:j]
for key in keys:
om.dict[key] = self.dict[key]
return om
def __setslice__(self, i, j, other):
""" Set the slice [i:j] of the object to the contents of the
OrderedMapping object other.
"""
# om[1:3] = other OrderedMapping
if not isinstance(other,OrderedMapping):
raise TypeError,'assigned object must be an OrderedMapping'
# del om[1:3]
keys = self.list[i:j]
for key in keys:
del self.dict[key]
# insert new mappings
otherkeys = other.list
self.list[i:j] = otherkeys
for key in otherkeys:
self.dict[key] = other.dict[key]
def __delslice__(self, i, j):
""" Delete the slice [i:j] of the object.
"""
# del om[1:3]
keys = self.list[i:j]
for key in keys:
del self.dict[key]
del self.list[i:j]
def __add__(self, other):
""" Concatenate the contents of an OrderedMapping object other
to self and return the result as new OrderedMapping object.
"""
# self + other OrderedMapping
if not isinstance(other,OrderedMapping):
raise TypeError,'other object must be an OrderedMapping'
om = OrderedMapping()
om.dict = self.dict.copy()
for key in other.list:
if om.has_key(key):
raise ValueError,\
'result would have more than one value for key ' + repr(key)
om.dict.update(other.dict)
om.list = self.list + other.list
return om
__radd__ = __add__
def append(self, item):
""" Append an item (key, value) to the object and return
the position of the new value.
The item is addressable under key and the position
returned by the method.
"""
# runtime O(1)
key,value = item
if self.dict.has_key(key):
raise ValueError,'more than one value for key ' + repr(key)
self.list.append(key)
self.dict[key] = value
return len(self.list) - 1
def insert(self, keyindex, item):
""" Returns the object at position keyindex.
keyindex may either be an integer to index an object by
position or an arbitrary key object which is then used for
dictionary like lookup.
"""
key,value = item
if self.dict.has_key(key):
raise ValueError,'more than one value for key ' + repr(key)
if type(keyindex) == types.IntType:
# om.insert(0,('a','b'))
self.list.insert(keyindex,key)
self.dict[key] = value
else:
# om.insert('a',('b','c'))
index = self.list.index(key)
self.list.insert(index,key)
self.dict[key] = value
def remove(self, value):
""" Remove all occurrences of value from the object.
"""
for i,key in reverse(irange(self.list)):
if self.dict[key] == value:
del self.list[i]
del self.dict[key]
def count(self, value):
""" Count all occurrences of value from the object.
"""
count = 0
for key in self.list:
if self.dict[key] == value:
count = count + 1
return count
def index(self, value):
""" Return the index of the first occurrences of value in the
object.
"""
for index,key in irange(self.list):
if self.dict[key] == value:
return index
raise ValueError,repr(value) + ' not as value in OrderedMapping'
def keyindex(self, key):
""" Returns the object at position keyindex.
keyindex may either be an integer to index an object by
position or an arbitrary key object which is then used for
dictionary like lookup.
"""
return self.list.index(key)
def reverse(self):
""" Reverses the order of the keys.
"""
self.list.reverse()
def sort(self, *args):
""" Sorts the keys.
This changes the order of the stored items.
"""
apply(self.list.sort, args)
def clear(self):
""" Clear the object.
"""
self.list = []
self.dict.clear()
def copy(self):
""" Return a shallow copy of the object.
"""
import copy
return copy.copy(self)
def key(self,index):
""" Returns the key at position index.
"""
return self.list[index]
def keys(self):
""" Returns a list of keys in the order they are maintained
by the object.
"""
return self.list
def items(self):
""" Returns a list of (key,value) tuples in the order they are
maintained by the object.
"""
keys = self.list
values = extract(self.dict,keys)
return tuples(keys,values)
def values(self):
""" Returns a list of values in the order they are maintained
by the object.
"""
keys = self.list
values = extract(self.dict, keys)
return values
def has_key(self, key):
""" Returns 1/0 depending on whether the given key exists
or not.
"""
return self.dict.has_key(key)
#def update(self, other):
# raise RuntimeError,'not implemented'
def get(self, key, default=None):
""" Return the value for key or default in case it is not found.
This only works for non-index keys.
"""
return self.dict.get(key,default)
def filter(self,filterfct):
""" Filters the mapping's keys and values according to
a filterfct.
The filterfct is called with (k,v) for each key value pair
in the current order. If its return value is non-None, it
is appended to the result list.
The list is returned to the caller.
"""
dict = self.dict
l = []
append = l.append
for k in self.list:
v = dict[k]
result = filterfct(k,v)
if result is not None:
append(result)
return l
###
class OrderedMappingWithDefault(OrderedMapping):
""" OrderedMapping with default values.
This version returns self._default in case a lookup fails.
self._default is set to '' for this base class.
"""
_default = ''
def __getitem__(self, keyindex,
IntType=types.IntType,type=type):
""" Returns the object at position keyindex.
If not found, ._default is returned.
keyindex may either be an integer to index an object by
position or an arbitrary key object which is then used for
dictionary like lookup.
"""
# runtime O(1)
if type(keyindex) is IntType:
# om[0]
try:
key = self.list[keyindex]
except IndexError:
return self._default
else:
return self.dict[key]
else:
# om['bar']
try:
return self.dict[keyindex]
except KeyError:
return self._default
freeze(OrderedMappingWithDefault)
###
if __name__ == '__main__':
o = OrderedMapping()
o['a'] = 'b'
o['b'] = 'c'
o['c'] = 'd'
p = OrderedMapping()
p['A'] = 'B'
p['B'] = 'C'
r = OrderedMapping(('1',1),('2',2),('3',3))
|