Changeset 1934 for trunk/packages/invirt-base/python
- Timestamp:
- Dec 28, 2008, 7:20:07 PM (16 years ago)
- Location:
- trunk/packages/invirt-base/python/invirt
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/packages/invirt-base/python/invirt/common.py
r1623 r1934 5 5 import contextlib as clib 6 6 7 class InvirtConfigError(AttributeError): 8 pass 9 7 10 class struct(object): 8 11 'A simple namespace object.' 9 def __init__(self, d = {}, **kwargs):10 'd is the dictionary to update my __dict__ with.'12 def __init__(self, d = {}, __prefix = None, **kwargs): 13 'd is the dictionary or the items-iterable to update my __dict__ with.' 11 14 self.__dict__.update(d) 12 15 self.__dict__.update(kwargs) 16 self.__prefix = __prefix 17 def __getattr__(self, key): 18 # XX ideally these would point a frame higher on the stack. 19 prefix = self.__prefix 20 if prefix is not None: 21 raise InvirtConfigError('missing configuration variable %s%s' 22 % (prefix, key)) 23 else: 24 raise AttributeError("anonymous struct has no member '%s'" 25 % (key,)) 13 26 14 def dicts2struct(x ):27 def dicts2struct(x, prefix = None): 15 28 """ 16 29 Given a tree of lists/dicts, perform a deep traversal to transform all the 17 30 dicts to structs. 18 31 """ 32 if prefix is not None: 33 def newprefix(k): return prefix + str(k) + '.' 34 else: 35 def newprefix(k): return prefix 19 36 if type(x) == dict: 20 return struct((k, dicts2struct(v)) for k,v in x.iteritems()) 37 return struct(((k, dicts2struct(v, newprefix(k))) 38 for k,v in x.iteritems()), 39 prefix) 21 40 elif type(x) == list: 22 return [dicts2struct(v ) for v in x]41 return [dicts2struct(v, newprefix(i)) for i, v in enumerate(x)] 23 42 else: 24 43 return x … … 68 87 'list': [ 'atom', {'key': 'value'} ] 69 88 } 70 structs = dicts2struct(dicts )89 structs = dicts2struct(dicts, '') 71 90 self.assertEqual(structs.atom, dicts['atom']) 72 91 self.assertEqual(structs.dict.atom, dicts['dict']['atom']) -
trunk/packages/invirt-base/python/invirt/config.py
r1933 r1934 141 141 142 142 dicts = load() 143 structs = dicts2struct(dicts )143 structs = dicts2struct(dicts, '') 144 144 145 145 # vim:et:sw=4:ts=4
Note: See TracChangeset
for help on using the changeset viewer.