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):
33 """An internal mapping container. 35 This class 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))
56 history = property(
lambda x: x._history)
57 """History (read-only). 64 return len(self.
_dict)
67 return iter(self.
_dict)
70 return k
in self.
_dict 72 def __setitem__(self, k, x, at=None, label="setitem", setHistory=True):
74 msg =
"Cannot modify a frozen Config. "\
75 "Attempting to set item at key %r to value %s" % (k, x)
79 k = _autocast(k, self.
_field.keytype)
80 if type(k) != self.
_field.keytype:
81 msg =
"Key %r is of type %s, expected type %s" % \
82 (k, _typeStr(k), _typeStr(self.
_field.keytype))
86 x = _autocast(x, self.
_field.itemtype)
87 if self.
_field.itemtype
is None:
88 if type(x)
not in self.
_field.supportedTypes
and x
is not None:
89 msg =
"Value %s at key %r is of invalid type %s" % (x, k, _typeStr(x))
92 if type(x) != self.
_field.itemtype
and x
is not None:
93 msg =
"Value %s at key %r is of incorrect type %s. Expected type %s" % \
94 (x, k, _typeStr(x), _typeStr(self.
_field.itemtype))
98 if self.
_field.itemCheck
is not None and not self.
_field.itemCheck(x):
99 msg =
"Item at key %r is not a valid value: %s" % (k, x)
109 def __delitem__(self, k, at=None, label="delitem", setHistory=True):
112 "Cannot modify a frozen Config")
121 return repr(self.
_dict)
124 return str(self.
_dict)
127 if hasattr(getattr(self.__class__, attr,
None),
'__set__'):
129 object.__setattr__(self, attr, value)
130 elif attr
in self.__dict__
or attr
in [
"_field",
"_config",
"_history",
"_dict",
"__doc__"]:
132 object.__setattr__(self, attr, value)
135 msg =
"%s has no attribute %s" % (_typeStr(self.
_field), attr)
140 """A configuration field (`~lsst.pex.config.Field` subclass) that maps keys 143 The types of both items and keys are restricted to these builtin types: 144 `int`, `float`, `complex`, `bool`, and `str`). All keys share the same type 145 and all values share the same type. Keys can have a different type from 151 A documentation string that describes the configuration field. 152 keytype : {`int`, `float`, `complex`, `bool`, `str`} 153 The type of the mapping keys. All keys must have this type. 154 itemtype : {`int`, `float`, `complex`, `bool`, `str`} 155 Type of the mapping values. 156 default : `dict`, optional 158 optional : `bool`, optional 159 If `True`, the field doesn't need to have a set value. 161 A function that validates the dictionary as a whole. 163 A function that validates individual mapping values. 164 deprecated : None or `str`, optional 165 A description of why this Field is deprecated, including removal date. 166 If not None, the string is appended to the docstring for this Field. 182 This field maps has `str` keys and `int` values: 184 >>> from lsst.pex.config import Config, DictField 185 >>> class MyConfig(Config): 186 ... field = DictField( 187 ... doc="Example string-to-int mapping field.", 188 ... keytype=str, itemtype=int, 191 >>> config = MyConfig() 192 >>> config.field['myKey'] = 42 193 >>> print(config.field) 199 def __init__(self, doc, keytype, itemtype, default=None, optional=False, dictCheck=None, itemCheck=None,
202 self.
_setup(doc=doc, dtype=Dict, default=default, check=
None,
203 optional=optional, source=source, deprecated=deprecated)
205 raise ValueError(
"'keytype' %s is not a supported type" %
207 elif itemtype
is not None and itemtype
not in self.
supportedTypes:
208 raise ValueError(
"'itemtype' %s is not a supported type" %
210 if dictCheck
is not None and not hasattr(dictCheck,
"__call__"):
211 raise ValueError(
"'dictCheck' must be callable")
212 if itemCheck
is not None and not hasattr(itemCheck,
"__call__"):
213 raise ValueError(
"'itemCheck' must be callable")
221 """Validate the field's value (for internal use only). 225 instance : `lsst.pex.config.Config` 226 The configuration that contains this field. 231 `True` is returned if the field passes validation criteria (see 232 *Notes*). Otherwise `False`. 236 This method validates values according to the following criteria: 238 - A non-optional field is not `None`. 239 - If a value is not `None`, is must pass the `ConfigField.dictCheck` 240 user callback functon. 242 Individual item checks by the `ConfigField.itemCheck` user callback 243 function are done immediately when the value is set on a key. Those 244 checks are not repeated by this method. 246 Field.validate(self, instance)
248 if value
is not None and self.
dictCheck is not None \
250 msg =
"%s is not a valid value" % str(value)
253 def __set__(self, instance, value, at=None, label="assignment"):
255 msg =
"Cannot modify a frozen Config. "\
256 "Attempting to set field to value %s" % value
261 if value
is not None:
262 value = self.
DictClass(instance, self, value, at=at, label=label)
264 history = instance._history.setdefault(self.name, [])
265 history.append((value, at, label))
267 instance._storage[self.name] = value
270 """Convert this field's key-value pairs into a regular `dict`. 274 instance : `lsst.pex.config.Config` 275 The configuration that contains this field. 279 result : `dict` or `None` 280 If this field has a value of `None`, then this method returns 281 `None`. Otherwise, this method returns the field's value as a 282 regular Python `dict`. 285 return dict(value)
if value
is not None else None 287 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
288 """Compare two fields for equality. 290 Used by `lsst.pex.ConfigDictField.compare`. 294 instance1 : `lsst.pex.config.Config` 295 Left-hand side config instance to compare. 296 instance2 : `lsst.pex.config.Config` 297 Right-hand side config instance to compare. 299 If `True`, this function returns as soon as an inequality if found. 301 Relative tolerance for floating point comparisons. 303 Absolute tolerance for floating point comparisons. 305 A callable that takes a string, used (possibly repeatedly) to 311 `True` if the fields are equal, `False` otherwise. 315 Floating point comparisons are performed by `numpy.allclose`. 317 d1 = getattr(instance1, self.name)
318 d2 = getattr(instance2, self.name)
320 _joinNamePath(instance1._name, self.name),
321 _joinNamePath(instance2._name, self.name)
323 if not compareScalars(
"isnone for %s" % name, d1
is None, d2
is None, output=output):
325 if d1
is None and d2
is None:
327 if not compareScalars(
"keys for %s" % name, set(d1.keys()), set(d2.keys()), output=output):
330 for k, v1
in d1.items():
333 rtol=rtol, atol=atol, output=output)
334 if not result
and shortcut:
336 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 __init__(self, doc, keytype, itemtype, default=None, optional=False, dictCheck=None, itemCheck=None, deprecated=None)
def __get__(self, instance, owner=None, at=None, label="default")
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 toDict(self, instance)
def _setup(self, doc, dtype, default, check, optional, source, deprecated)
def getComparisonName(name1, name2)
def __set__(self, instance, value, at=None, label="assignment")