22 import traceback, copy
25 from .config
import Config, Field, FieldValidationError, _typeStr, _autocast, _joinNamePath
26 from .comparison
import *
30 class Dict(collections.MutableMapping):
32 Config-Internal mapping container
33 Emulates a dict, but adds validation and provenance.
36 def __init__(self, config, field, value, at, label, setHistory=True):
40 self.
_history = self._config._history.setdefault(self._field.name, [])
46 self.
__setitem__(k, value[k], at=at, label=label, setHistory=
False)
48 msg =
"Value %s is of incorrect type %s. Mapping type expected."%\
52 self._history.append((dict(self.
_dict), at, label))
58 history = property(
lambda x: x._history)
68 def __setitem__(self, k, x, at=None, label="setitem", setHistory=True):
69 if self._config._frozen:
70 msg =
"Cannot modify a frozen Config. "\
71 "Attempting to set item at key %r to value %s"%(k, x)
76 if type(k) != self._field.keytype:
77 msg =
"Key %r is of type %s, expected type %s"%\
83 if type(x) != self._field.itemtype
and x
is not None:
84 msg =
"Value %s at key %r is of incorrect type %s. Expected type %s"%\
89 if self._field.itemCheck
is not None and not self._field.itemCheck(x):
90 msg=
"Item at key %r is not a valid value: %s"%(k, x)
94 at = traceback.extract_stack()[:-1]
98 self._history.append((dict(self.
_dict), at, label))
100 def __delitem__(self, k, at=None, label="delitem", setHistory=True):
101 if self._config._frozen:
103 "Cannot modify a frozen Config")
108 at = traceback.extract_stack()[:-1]
109 self._history.append((dict(self.
_dict), at, label))
116 if hasattr(getattr(self.__class__, attr,
None),
'__set__'):
118 object.__setattr__(self, attr, value)
119 elif attr
in self.__dict__
or attr
in [
"_field",
"_config",
"_history",
"_dict",
"__doc__"]:
121 object.__setattr__(self, attr, value)
130 Defines a field which is a mapping of values
132 Both key and item types are restricted to builtin POD types:
133 (int, float, complex, bool, str)
135 Users can provide two check functions:
136 dictCheck: used to validate the dict as a whole, and
137 itemCheck: used to validate each item individually
139 For example to define a field which is a mapping from names to int values:
141 class MyConfig(Config):
143 doc="example string-to-int mapping field",
144 keytype=str, itemtype=int,
149 def __init__(self, doc, keytype, itemtype, default=None, optional=False, dictCheck=None, itemCheck=None):
150 source = traceback.extract_stack(limit=2)[0]
151 self._setup( doc=doc, dtype=Dict, default=default, check=
None,
152 optional=optional, source=source)
153 if keytype
not in self.supportedTypes:
154 raise ValueError(
"'keytype' %s is not a supported type"%\
156 elif itemtype
not in self.supportedTypes:
157 raise ValueError(
"'itemtype' %s is not a supported type"%\
159 if dictCheck
is not None and not hasattr(dictCheck,
"__call__"):
160 raise ValueError(
"'dictCheck' must be callable")
161 if itemCheck
is not None and not hasattr(itemCheck,
"__call__"):
162 raise ValueError(
"'itemCheck' must be callable")
171 DictField validation ensures that non-optional fields are not None,
172 and that non-None values comply with dictCheck.
173 Individual Item checks are applied at set time and are not re-checked.
175 Field.validate(self, instance)
176 value = self.__get__(instance)
177 if value
is not None and self.
dictCheck is not None \
179 msg =
"%s is not a valid value"%str(value)
180 raise FieldValidationError(self, instance, msg)
183 def __set__(self, instance, value, at=None, label="assignment"):
185 msg =
"Cannot modify a frozen Config. "\
186 "Attempting to set field to value %s"%value
187 raise FieldValidationError(self, instance, msg)
190 at = traceback.extract_stack()[:-1]
191 if value
is not None:
192 value = self.
DictClass(instance, self, value, at=at, label=label)
194 history = instance._history.setdefault(self.name, [])
195 history.append((value, at, label))
197 instance._storage[self.name] = value
200 value = self.__get__(instance)
201 return dict(value)
if value
is not None else None
203 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
204 """Helper function for Config.compare; used to compare two fields for equality.
206 @param[in] instance1 LHS Config instance to compare.
207 @param[in] instance2 RHS Config instance to compare.
208 @param[in] shortcut If True, return as soon as an inequality is found.
209 @param[in] rtol Relative tolerance for floating point comparisons.
210 @param[in] atol Absolute tolerance for floating point comparisons.
211 @param[in] output If not None, a callable that takes a string, used (possibly repeatedly)
212 to report inequalities.
214 Floating point comparisons are performed by numpy.allclose; refer to that for details.
216 d1 = getattr(instance1, self.name)
217 d2 = getattr(instance2, self.name)
222 if not compareScalars(
"isnone for %s" % name, d1
is None, d2
is None, output=output):
224 if d1
is None and d2
is None:
226 if not compareScalars(
"keys for %s" % name, d1.keys(), d2.keys(), output=output):
229 for k, v1
in d1.iteritems():
232 rtol=rtol, atol=atol, output=output)
233 if not result
and shortcut:
235 equal = equal
and result