22 __all__ = [
"DictField"]
24 import collections.abc
26 from .config
import Field, FieldValidationError, _typeStr, _autocast, _joinNamePath
27 from .comparison
import getComparisonName, compareScalars
28 from .callStack
import getCallStack, getStackFrame
31 class Dict(collections.abc.MutableMapping):
32 """An internal mapping container. 34 This class emulates a `dict`, but adds validation and provenance. 37 def __init__(self, config, field, value, at, label, setHistory=True):
47 self.
__setitem__(k, value[k], at=at, label=label, setHistory=
False)
49 msg =
"Value %s is of incorrect type %s. Mapping type expected." % \
50 (value, _typeStr(value))
55 history = property(
lambda x: x._history)
56 """History (read-only). 63 return len(self.
_dict)
66 return iter(self.
_dict)
69 return k
in self.
_dict 71 def __setitem__(self, k, x, at=None, label="setitem", setHistory=True):
73 msg =
"Cannot modify a frozen Config. "\
74 "Attempting to set item at key %r to value %s" % (k, x)
78 k = _autocast(k, self.
_field.keytype)
79 if type(k) != self.
_field.keytype:
80 msg =
"Key %r is of type %s, expected type %s" % \
81 (k, _typeStr(k), _typeStr(self.
_field.keytype))
85 x = _autocast(x, self.
_field.itemtype)
86 if self.
_field.itemtype
is None:
87 if type(x)
not in self.
_field.supportedTypes
and x
is not None:
88 msg =
"Value %s at key %r is of invalid type %s" % (x, k, _typeStr(x))
91 if type(x) != self.
_field.itemtype
and x
is not None:
92 msg =
"Value %s at key %r is of incorrect type %s. Expected type %s" % \
93 (x, k, _typeStr(x), _typeStr(self.
_field.itemtype))
97 if self.
_field.itemCheck
is not None and not self.
_field.itemCheck(x):
98 msg =
"Item at key %r is not a valid value: %s" % (k, x)
108 def __delitem__(self, k, at=None, label="delitem", setHistory=True):
111 "Cannot modify a frozen Config")
120 return repr(self.
_dict)
123 return str(self.
_dict)
126 if hasattr(getattr(self.__class__, attr,
None),
'__set__'):
128 object.__setattr__(self, attr, value)
129 elif attr
in self.__dict__
or attr
in [
"_field",
"_config",
"_history",
"_dict",
"__doc__"]:
131 object.__setattr__(self, attr, value)
134 msg =
"%s has no attribute %s" % (_typeStr(self.
_field), attr)
139 """A configuration field (`~lsst.pex.config.Field` subclass) that maps keys 142 The types of both items and keys are restricted to these builtin types: 143 `int`, `float`, `complex`, `bool`, and `str`). All keys share the same type 144 and all values share the same type. Keys can have a different type from 150 A documentation string that describes the configuration field. 151 keytype : {`int`, `float`, `complex`, `bool`, `str`} 152 The type of the mapping keys. All keys must have this type. 153 itemtype : {`int`, `float`, `complex`, `bool`, `str`} 154 Type of the mapping values. 155 default : `dict`, optional 157 optional : `bool`, optional 158 If `True`, the field doesn't need to have a set value. 160 A function that validates the dictionary as a whole. 162 A function that validates individual mapping values. 163 deprecated : None or `str`, optional 164 A description of why this Field is deprecated, including removal date. 165 If not None, the string is appended to the docstring for this Field. 181 This field maps has `str` keys and `int` values: 183 >>> from lsst.pex.config import Config, DictField 184 >>> class MyConfig(Config): 185 ... field = DictField( 186 ... doc="Example string-to-int mapping field.", 187 ... keytype=str, itemtype=int, 190 >>> config = MyConfig() 191 >>> config.field['myKey'] = 42 192 >>> print(config.field) 198 def __init__(self, doc, keytype, itemtype, default=None, optional=False, dictCheck=None, itemCheck=None,
201 self.
_setup(doc=doc, dtype=Dict, default=default, check=
None,
202 optional=optional, source=source, deprecated=deprecated)
204 raise ValueError(
"'keytype' %s is not a supported type" %
206 elif itemtype
is not None and itemtype
not in self.
supportedTypes:
207 raise ValueError(
"'itemtype' %s is not a supported type" %
209 if dictCheck
is not None and not hasattr(dictCheck,
"__call__"):
210 raise ValueError(
"'dictCheck' must be callable")
211 if itemCheck
is not None and not hasattr(itemCheck,
"__call__"):
212 raise ValueError(
"'itemCheck' must be callable")
220 """Validate the field's value (for internal use only). 224 instance : `lsst.pex.config.Config` 225 The configuration that contains this field. 230 `True` is returned if the field passes validation criteria (see 231 *Notes*). Otherwise `False`. 235 This method validates values according to the following criteria: 237 - A non-optional field is not `None`. 238 - If a value is not `None`, is must pass the `ConfigField.dictCheck` 239 user callback functon. 241 Individual item checks by the `ConfigField.itemCheck` user callback 242 function are done immediately when the value is set on a key. Those 243 checks are not repeated by this method. 245 Field.validate(self, instance)
247 if value
is not None and self.
dictCheck is not None \
249 msg =
"%s is not a valid value" % str(value)
252 def __set__(self, instance, value, at=None, label="assignment"):
254 msg =
"Cannot modify a frozen Config. "\
255 "Attempting to set field to value %s" % value
260 if value
is not None:
261 value = self.
DictClass(instance, self, value, at=at, label=label)
263 history = instance._history.setdefault(self.name, [])
264 history.append((value, at, label))
266 instance._storage[self.name] = value
269 """Convert this field's key-value pairs into a regular `dict`. 273 instance : `lsst.pex.config.Config` 274 The configuration that contains this field. 278 result : `dict` or `None` 279 If this field has a value of `None`, then this method returns 280 `None`. Otherwise, this method returns the field's value as a 281 regular Python `dict`. 284 return dict(value)
if value
is not None else None 286 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
287 """Compare two fields for equality. 289 Used by `lsst.pex.ConfigDictField.compare`. 293 instance1 : `lsst.pex.config.Config` 294 Left-hand side config instance to compare. 295 instance2 : `lsst.pex.config.Config` 296 Right-hand side config instance to compare. 298 If `True`, this function returns as soon as an inequality if found. 300 Relative tolerance for floating point comparisons. 302 Absolute tolerance for floating point comparisons. 304 A callable that takes a string, used (possibly repeatedly) to 310 `True` if the fields are equal, `False` otherwise. 314 Floating point comparisons are performed by `numpy.allclose`. 316 d1 = getattr(instance1, self.name)
317 d2 = getattr(instance2, self.name)
319 _joinNamePath(instance1._name, self.name),
320 _joinNamePath(instance2._name, self.name)
322 if not compareScalars(
"isnone for %s" % name, d1
is None, d2
is None, output=output):
324 if d1
is None and d2
is None:
326 if not compareScalars(
"keys for %s" % name, set(d1.keys()), set(d2.keys()), output=output):
329 for k, v1
in d1.items():
332 rtol=rtol, atol=atol, output=output)
333 if not result
and shortcut:
335 equal = equal
and result
def __setattr__(self, attr, value, at=None, label="assignment")
def toDict(self, instance)
def __init__(self, config, field, value, at, label, setHistory=True)
def validate(self, instance)
def __contains__(self, k)
def __init__(self, doc, keytype, itemtype, default=None, optional=False, dictCheck=None, itemCheck=None, deprecated=None)
def getStackFrame(relative=0)
def __get__(self, instance, owner=None, at=None, label="default")
def __set__(self, instance, value, at=None, label="assignment")
def __setitem__(self, k, x, at=None, label="setitem", setHistory=True)
def getComparisonName(name1, name2)
def __delitem__(self, k, at=None, label="delitem", setHistory=True)
def compareScalars(name, v1, v2, output, rtol=1E-8, atol=1E-8, dtype=None)
def _setup(self, doc, dtype, default, check, optional, source, deprecated)