23 __all__ = [
"DictField"]
25 import collections.abc
27 from .config
import Field, FieldValidationError, _typeStr, _autocast, _joinNamePath
28 from .comparison
import getComparisonName, compareScalars
29 from .callStack
import getCallStack, getStackFrame
32 class Dict(collections.abc.MutableMapping):
34 Config-Internal mapping container 35 Emulates a dict, but adds validation and provenance. 38 def __init__(self, config, field, value, at, label, setHistory=True):
48 self.
__setitem__(k, value[k], at=at, label=label, setHistory=
False)
50 msg =
"Value %s is of incorrect type %s. Mapping type expected." % \
51 (value, _typeStr(value))
59 history = property(
lambda x: x._history)
65 return len(self.
_dict)
68 return iter(self.
_dict)
71 return k
in self.
_dict 73 def __setitem__(self, k, x, at=None, label="setitem", setHistory=True):
75 msg =
"Cannot modify a frozen Config. "\
76 "Attempting to set item at key %r to value %s" % (k, x)
80 k = _autocast(k, self.
_field.keytype)
81 if type(k) != self.
_field.keytype:
82 msg =
"Key %r is of type %s, expected type %s" % \
83 (k, _typeStr(k), _typeStr(self.
_field.keytype))
87 x = _autocast(x, self.
_field.itemtype)
88 if self.
_field.itemtype
is None:
89 if type(x)
not in self.
_field.supportedTypes
and x
is not None:
90 msg =
"Value %s at key %r is of invalid type %s" % (x, k, _typeStr(x))
93 if type(x) != self.
_field.itemtype
and x
is not None:
94 msg =
"Value %s at key %r is of incorrect type %s. Expected type %s" % \
95 (x, k, _typeStr(x), _typeStr(self.
_field.itemtype))
99 if self.
_field.itemCheck
is not None and not self.
_field.itemCheck(x):
100 msg =
"Item at key %r is not a valid value: %s" % (k, x)
110 def __delitem__(self, k, at=None, label="delitem", setHistory=True):
113 "Cannot modify a frozen Config")
122 return repr(self.
_dict)
125 return str(self.
_dict)
128 if hasattr(getattr(self.__class__, attr,
None),
'__set__'):
130 object.__setattr__(self, attr, value)
131 elif attr
in self.__dict__
or attr
in [
"_field",
"_config",
"_history",
"_dict",
"__doc__"]:
133 object.__setattr__(self, attr, value)
136 msg =
"%s has no attribute %s" % (_typeStr(self.
_field), attr)
142 Defines a field which is a mapping of values 144 Both key and item types are restricted to builtin POD types: 145 (int, float, complex, bool, str) 147 Users can provide two check functions: 148 dictCheck: used to validate the dict as a whole, and 149 itemCheck: used to validate each item individually 151 For example to define a field which is a mapping from names to int values: 153 class MyConfig(Config): 155 doc="example string-to-int mapping field", 156 keytype=str, itemtype=int, 161 def __init__(self, doc, keytype, itemtype, default=None, optional=False, dictCheck=None, itemCheck=None):
163 self.
_setup(doc=doc, dtype=Dict, default=default, check=
None,
164 optional=optional, source=source)
166 raise ValueError(
"'keytype' %s is not a supported type" %
168 elif itemtype
is not None and itemtype
not in self.
supportedTypes:
169 raise ValueError(
"'itemtype' %s is not a supported type" %
171 if dictCheck
is not None and not hasattr(dictCheck,
"__call__"):
172 raise ValueError(
"'dictCheck' must be callable")
173 if itemCheck
is not None and not hasattr(itemCheck,
"__call__"):
174 raise ValueError(
"'itemCheck' must be callable")
183 DictField validation ensures that non-optional fields are not None, 184 and that non-None values comply with dictCheck. 185 Individual Item checks are applied at set time and are not re-checked. 187 Field.validate(self, instance)
189 if value
is not None and self.
dictCheck is not None \
191 msg =
"%s is not a valid value" % str(value)
194 def __set__(self, instance, value, at=None, label="assignment"):
196 msg =
"Cannot modify a frozen Config. "\
197 "Attempting to set field to value %s" % value
202 if value
is not None:
203 value = self.
DictClass(instance, self, value, at=at, label=label)
205 history = instance._history.setdefault(self.name, [])
206 history.append((value, at, label))
208 instance._storage[self.name] = value
212 return dict(value)
if value
is not None else None 214 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
215 """Helper function for Config.compare; used to compare two fields for equality. 217 @param[in] instance1 LHS Config instance to compare. 218 @param[in] instance2 RHS Config instance to compare. 219 @param[in] shortcut If True, return as soon as an inequality is found. 220 @param[in] rtol Relative tolerance for floating point comparisons. 221 @param[in] atol Absolute tolerance for floating point comparisons. 222 @param[in] output If not None, a callable that takes a string, used (possibly repeatedly) 223 to report inequalities. 225 Floating point comparisons are performed by numpy.allclose; refer to that for details. 227 d1 = getattr(instance1, self.name)
228 d2 = getattr(instance2, self.name)
230 _joinNamePath(instance1._name, self.name),
231 _joinNamePath(instance2._name, self.name)
233 if not compareScalars(
"isnone for %s" % name, d1
is None, d2
is None, output=output):
235 if d1
is None and d2
is None:
237 if not compareScalars(
"keys for %s" % name, set(d1.keys()), set(d2.keys()), output=output):
240 for k, v1
in d1.items():
243 rtol=rtol, atol=atol, output=output)
244 if not result
and shortcut:
246 equal = equal
and result
def __init__(self, config, field, value, at, label, setHistory=True)
def __setitem__(self, k, x, at=None, label="setitem", setHistory=True)
def __get__(self, instance, owner=None, at=None, label="default")
def _setup(self, doc, dtype, default, check, optional, source)
def getStackFrame(relative=0)
def __delitem__(self, k, at=None, label="delitem", setHistory=True)
def validate(self, instance)
def __contains__(self, k)
def __setattr__(self, attr, value, at=None, label="assignment")
def compareScalars(name, v1, v2, output, rtol=1E-8, atol=1E-8, dtype=None)
def __init__(self, doc, keytype, itemtype, default=None, optional=False, dictCheck=None, itemCheck=None)
def toDict(self, instance)
def getComparisonName(name1, name2)
def __set__(self, instance, value, at=None, label="assignment")