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)
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)
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. 179 This field maps has `str` keys and `int` values: 181 >>> from lsst.pex.config import Config, DictField 182 >>> class MyConfig(Config): 183 ... field = DictField( 184 ... doc="Example string-to-int mapping field.", 185 ... keytype=str, itemtype=int, 188 >>> config = MyConfig() 189 >>> config.field['myKey'] = 42 190 >>> print(config.field) 196 def __init__(self, doc, keytype, itemtype, default=None, optional=False, dictCheck=None, itemCheck=None):
198 self.
_setup(doc=doc, dtype=Dict, default=default, check=
None,
199 optional=optional, source=source)
201 raise ValueError(
"'keytype' %s is not a supported type" %
203 elif itemtype
is not None and itemtype
not in self.
supportedTypes:
204 raise ValueError(
"'itemtype' %s is not a supported type" %
206 if dictCheck
is not None and not hasattr(dictCheck,
"__call__"):
207 raise ValueError(
"'dictCheck' must be callable")
208 if itemCheck
is not None and not hasattr(itemCheck,
"__call__"):
209 raise ValueError(
"'itemCheck' must be callable")
217 """Validate the field's value (for internal use only). 221 instance : `lsst.pex.config.Config` 222 The configuration that contains this field. 227 `True` is returned if the field passes validation criteria (see 228 *Notes*). Otherwise `False`. 232 This method validates values according to the following criteria: 234 - A non-optional field is not `None`. 235 - If a value is not `None`, is must pass the `ConfigField.dictCheck` 236 user callback functon. 238 Individual item checks by the `ConfigField.itemCheck` user callback 239 function are done immediately when the value is set on a key. Those 240 checks are not repeated by this method. 242 Field.validate(self, instance)
244 if value
is not None and self.
dictCheck is not None \
246 msg =
"%s is not a valid value" %
str(value)
249 def __set__(self, instance, value, at=None, label="assignment"):
251 msg =
"Cannot modify a frozen Config. "\
252 "Attempting to set field to value %s" % value
257 if value
is not None:
258 value = self.
DictClass(instance, self, value, at=at, label=label)
260 history = instance._history.setdefault(self.name, [])
261 history.append((value, at, label))
263 instance._storage[self.name] = value
266 """Convert this field's key-value pairs into a regular `dict`. 270 instance : `lsst.pex.config.Config` 271 The configuration that contains this field. 275 result : `dict` or `None` 276 If this field has a value of `None`, then this method returns 277 `None`. Otherwise, this method returns the field's value as a 278 regular Python `dict`. 281 return dict(value)
if value
is not None else None 283 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
284 """Compare two fields for equality. 286 Used by `lsst.pex.ConfigDictField.compare`. 290 instance1 : `lsst.pex.config.Config` 291 Left-hand side config instance to compare. 292 instance2 : `lsst.pex.config.Config` 293 Right-hand side config instance to compare. 295 If `True`, this function returns as soon as an inequality if found. 297 Relative tolerance for floating point comparisons. 299 Absolute tolerance for floating point comparisons. 301 A callable that takes a string, used (possibly repeatedly) to 307 `True` if the fields are equal, `False` otherwise. 311 Floating point comparisons are performed by `numpy.allclose`. 313 d1 = getattr(instance1, self.name)
314 d2 = getattr(instance2, self.name)
316 _joinNamePath(instance1._name, self.name),
317 _joinNamePath(instance2._name, self.name)
319 if not compareScalars(
"isnone for %s" % name, d1
is None, d2
is None, output=output):
321 if d1
is None and d2
is None:
326 for k, v1
in d1.items():
329 rtol=rtol, atol=atol, output=output)
330 if not result
and shortcut:
332 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)
std::shared_ptr< FrameSet > append(FrameSet const &first, FrameSet const &second)
Construct a FrameSet that performs two transformations in series.
daf::base::PropertySet * set
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")