Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-07-23 02:25:40

0001 # helper classes for sorted and fixed dicts
0002 class SortedKeysDict(dict):
0003     """a dict preserving order of keys"""
0004     # specialised __repr__ missing.
0005     def __init__(self,*args,**kw):
0006         dict.__init__(self,*args,**kw)
0007         self.list = list()
0008         if len(args) == 1:
0009             if not hasattr(args[0],'keys'):
0010                 s = set()
0011                 #must protect against adding the same key multiple times
0012                 for x,y in iter(args[0]):
0013                     if x not in s:
0014                         self.list.append(x)
0015                         s.add(x)
0016             else:
0017                 self.list = list(args[0].keys())
0018             return
0019         self.list = list(super(SortedKeysDict,self).keys())
0020 
0021     def __repr__(self):
0022         meat = ', '.join([ '%s: %s' % (repr(key), repr(val)) for key,val in self.items() ])
0023         return '{' + meat + '}'
0024     def __iter__(self):
0025         for key in self.list:
0026             yield key
0027     def __setitem__(self, key, value):
0028         dict.__setitem__(self, key, value)
0029         if not hasattr(self,'list'):
0030           self.list = list()
0031         if not key in self.list:
0032             self.list.append(key)
0033     def __delitem__(self, key):
0034         dict.__delitem__(self, key)
0035         self.list.remove(key)
0036     def items(self):
0037         return [(key, dict.__getitem__(self, key)) for key in self.list]
0038     def iteritems(self):
0039         for key in self.list:
0040             yield key, dict.__getitem__(self, key)
0041     def iterkeys(self):
0042         for key in self.list:
0043             yield key
0044     def itervalues(self):
0045         for key in self.list:
0046             yield dict.__getitem__(self,key)
0047     def keys(self):
0048         return self.list
0049     def values(self):
0050         return [ dict.__getitem__(self, key) for key in self.list]
0051 
0052 
0053 class SortedAndFixedKeysDict(SortedKeysDict):
0054     """a sorted dictionary with fixed/frozen keys"""
0055     def _blocked_attribute(obj):
0056         raise AttributeError("A SortedAndFixedKeysDict cannot be modified.")
0057     _blocked_attribute = property(_blocked_attribute)
0058     __delitem__ = __setitem__ = clear = _blocked_attribute
0059     pop = popitem = setdefault = update = _blocked_attribute
0060     def __new__(cls, *args, **kw):
0061         new = SortedKeysDict.__new__(cls)
0062         SortedKeysDict.__init__(new, *args, **kw)
0063         return new
0064     def __init__(self, *args, **kw):
0065         pass
0066     def __repr__(self):
0067         return "SortedAndFixedKeysDict(%s)" % SortedKeysDict.__repr__(self)
0068 
0069 
0070 #helper based on code from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/414283
0071 class FixedKeysDict(dict):
0072     def _blocked_attribute(obj):
0073         raise AttributeError("A FixedKeysDict cannot be modified.")
0074     _blocked_attribute = property(_blocked_attribute)
0075 
0076     __delitem__ = __setitem__ = clear = _blocked_attribute
0077     pop = popitem = setdefault = update = _blocked_attribute
0078     def __new__(cls, *args, **kw):
0079         new = dict.__new__(cls)
0080         dict.__init__(new, *args, **kw)
0081         return new
0082     def __init__(self, *args, **kw):
0083         pass
0084     def __repr__(self):
0085         return "FixedKeysDict(%s)" % dict.__repr__(self)
0086 
0087 
0088 if __name__=="__main__":
0089     import unittest
0090     class TestDictTypes(unittest.TestCase):
0091         def testFixedKeysDict(self):
0092             import operator
0093             d = FixedKeysDict({'a':1, 'b':[3]})
0094             self.assertEqual(d['a'],1)
0095             self.assertEqual(d['b'],[3])
0096             self.assertRaises(AttributeError,operator.setitem,*(d,'a',2))
0097             d['b'].append(2)
0098             self.assertEqual(d['b'],[3,2])
0099         
0100         def testSortedKeysDict(self):
0101             sd = SortedKeysDict()
0102             sd['a']=1
0103             sd['b']=2
0104             sd['c']=3
0105             sd['d']=4
0106             count =1
0107             for key in sd.iterkeys():
0108                 self.assertEqual(count,sd[key])
0109                 count +=1
0110             sd2 = SortedKeysDict(sd)
0111             count =1
0112             for key in sd2.iterkeys():
0113                 self.assertEqual(count,sd2[key])
0114                 count +=1
0115             sd3 = SortedKeysDict([('a',1),('b',2),('c',3),('d',4)])
0116             count =1
0117             for key in sd3.iterkeys():
0118                 self.assertEqual(count,sd3[key])
0119                 count +=1
0120             self.assertEqual(count-1,len(sd3))
0121             sd3 = SortedKeysDict(a=1,b=2,c=3,d=4)
0122             count =1
0123             for key in sd3.iterkeys():
0124                 count +=1
0125             self.assertEqual(count-1,len(sd3))
0126             sd['d']=5
0127             self.assertEqual(5,sd['d'])
0128             
0129         def testSortedAndFixedKeysDict(self):
0130             import operator
0131             sd = SortedAndFixedKeysDict({'a':1, 'b':[3]})
0132             self.assertEqual(sd['a'],1)
0133             self.assertEqual(sd['b'],[3])
0134             self.assertRaises(AttributeError,operator.setitem,*(sd,'a',2))
0135             sd = SortedAndFixedKeysDict([('a',1), ('b',2),('a',3)])
0136             self.assertEqual(['a','b'], [x for x in iter(sd)])
0137     unittest.main()