Ignore:
Timestamp:
Dec 28, 2008, 7:20:07 PM (16 years ago)
Author:
price
Message:

invirt.common: give clearer error message on missing config variable

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/packages/invirt-base/python/invirt/common.py

    r1623 r1934  
    55import contextlib as clib
    66
     7class InvirtConfigError(AttributeError):
     8    pass
     9
    710class struct(object):
    811    '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.'
    1114        self.__dict__.update(d)
    1215        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,))
    1326
    14 def dicts2struct(x):
     27def dicts2struct(x, prefix = None):
    1528    """
    1629    Given a tree of lists/dicts, perform a deep traversal to transform all the
    1730    dicts to structs.
    1831    """
     32    if prefix is not None:
     33        def newprefix(k): return prefix + str(k) + '.'
     34    else:
     35        def newprefix(k): return prefix
    1936    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)
    2140    elif type(x) == list:
    22         return [dicts2struct(v) for v in x]
     41        return [dicts2struct(v, newprefix(i)) for i, v in enumerate(x)]
    2342    else:
    2443        return x
     
    6887                'list': [ 'atom', {'key': 'value'} ]
    6988                }
    70         structs = dicts2struct(dicts)
     89        structs = dicts2struct(dicts, '')
    7190        self.assertEqual(structs.atom,        dicts['atom'])
    7291        self.assertEqual(structs.dict.atom,   dicts['dict']['atom'])
Note: See TracChangeset for help on using the changeset viewer.