comparison piecrust/configuration.py @ 138:b540d431f2da

Make configuration class more like `dict`, add support for merging `dicts`.
author Ludovic Chabant <ludovic@chabant.com>
date Sat, 29 Nov 2014 15:32:19 -0800
parents 10fc9c8bf682
children f98451237371
comparison
equal deleted inserted replaced
137:67a1c082d89d 138:b540d431f2da
16 def __init__(self, values=None, validate=True): 16 def __init__(self, values=None, validate=True):
17 if values is not None: 17 if values is not None:
18 self.setAll(values, validate) 18 self.setAll(values, validate)
19 else: 19 else:
20 self._values = None 20 self._values = None
21
22 def __contains__(self, key):
23 return self.has(key)
24
25 def __getitem__(self, key):
26 value = self.get(key)
27 if value is None:
28 raise KeyError()
29 return value
30
31 def __setitem__(self, key, value):
32 return self.set(key, value)
21 33
22 def setAll(self, values, validate=True): 34 def setAll(self, values, validate=True):
23 if validate: 35 if validate:
24 self._validateAll(values) 36 self._validateAll(values)
25 self._values = values 37 self._values = values
63 return False 75 return False
64 return True 76 return True
65 77
66 def merge(self, other): 78 def merge(self, other):
67 self._ensureLoaded() 79 self._ensureLoaded()
68 merge_dicts(self._values, other._values, 80
69 validator=self._validateValue) 81 if isinstance(other, dict):
82 other_values = other
83 elif isinstance(other, Configuration):
84 other_values = other._values
85 else:
86 raise Exception(
87 "Unsupported value type to merge: %s" % type(other))
88
89 merge_dicts(self._values, other_values,
90 validator=self._validateValue)
70 91
71 def _ensureLoaded(self): 92 def _ensureLoaded(self):
72 if self._values is None: 93 if self._values is None:
73 self._load() 94 self._load()
74 95