23 __all__ = [
"ListField"]
25 import collections.abc
27 from .config
import Field, FieldValidationError, _typeStr, _autocast, _joinNamePath
28 from .comparison
import compareScalars, getComparisonName
29 from .callStack
import getCallStack, getStackFrame
32 class List(collections.abc.MutableSequence):
33 """List collection used internally by `ListField`. 37 config : `lsst.pex.config.Config` 38 Config instance that contains the ``field``. 40 Instance of the `ListField` using this ``List``. 42 Sequence of values that are inserted into this ``List``. 43 at : `list` of `lsst.pex.config.callStack.StackFrame` 44 The call stack (created by `lsst.pex.config.callStack.getCallStack`). 46 Event label for the history. 47 setHistory : `bool`, optional 48 Enable setting the field's history, using the value of the ``at`` 49 parameter. Default is `True`. 54 Raised if an item in the ``value`` parameter does not have the 55 appropriate type for this field or does not pass the 56 `ListField.itemCheck` method of the ``field`` parameter. 59 def __init__(self, config, field, value, at, label, setHistory=True):
67 for i, x
in enumerate(value):
68 self.
insert(i, x, setHistory=
False)
70 msg =
"Value %s is of incorrect type %s. Sequence type expected" % (value, _typeStr(value))
76 """Validate an item to determine if it can be included in the list. 81 Index of the item in the `list`. 88 Raised if an item in the ``value`` parameter does not have the 89 appropriate type for this field or does not pass the field's 90 `ListField.itemCheck` method. 93 if not isinstance(x, self.
_field.itemtype)
and x
is not None:
94 msg =
"Item at position %d with value %s is of incorrect type %s. Expected %s" % \
95 (i, x, _typeStr(x), _typeStr(self.
_field.itemtype))
98 if self.
_field.itemCheck
is not None and not self.
_field.itemCheck(x):
99 msg =
"Item at position %d is not a valid value: %s" % (i, x)
103 """Sequence of items contained by the `List` (`list`). 107 history = property(
lambda x: x._history)
108 """Read-only history. 112 return x
in self.
_list 115 return len(self.
_list)
117 def __setitem__(self, i, x, at=None, label="setitem", setHistory=True):
120 "Cannot modify a frozen Config")
121 if isinstance(i, slice):
122 k, stop, step = i.indices(len(self))
123 for j, xj
in enumerate(x):
124 xj = _autocast(xj, self.
_field.itemtype)
129 x = _autocast(x, self.
_field.itemtype)
141 def __delitem__(self, i, at=None, label="delitem", setHistory=True):
144 "Cannot modify a frozen Config")
152 return iter(self.
_list)
154 def insert(self, i, x, at=None, label="insert", setHistory=True):
155 """Insert an item into the list at the given index. 160 Index where the item is inserted. 162 Item that is inserted. 163 at : `list` of `lsst.pex.config.callStack.StackFrame`, optional 164 The call stack (created by 165 `lsst.pex.config.callStack.getCallStack`). 166 label : `str`, optional 167 Event label for the history. 168 setHistory : `bool`, optional 169 Enable setting the field's history, using the value of the ``at`` 170 parameter. Default is `True`. 174 self.
__setitem__(slice(i, i), [x], at=at, label=label, setHistory=setHistory)
177 return repr(self.
_list)
180 return str(self.
_list)
184 if len(self) != len(other):
187 for i, j
in zip(self, other):
191 except AttributeError:
196 return not self.
__eq__(other)
199 if hasattr(getattr(self.__class__, attr,
None),
'__set__'):
201 object.__setattr__(self, attr, value)
202 elif attr
in self.__dict__
or attr
in [
"_field",
"_config",
"_history",
"_list",
"__doc__"]:
204 object.__setattr__(self, attr, value)
207 msg =
"%s has no attribute %s" % (_typeStr(self.
_field), attr)
212 """A configuration field (`~lsst.pex.config.Field` subclass) that contains 213 a list of values of a specific type. 218 A description of the field. 220 The data type of items in the list. 221 default : sequence, optional 222 The default items for the field. 223 optional : `bool`, optional 224 Set whether the field is *optional*. When `False`, 225 `lsst.pex.config.Config.validate` will fail if the field's value is 227 listCheck : callable, optional 228 A callable that validates the list as a whole. 229 itemCheck : callable, optional 230 A callable that validates individual items in the list. 231 length : `int`, optional 232 If set, this field must contain exactly ``length`` number of items. 233 minLength : `int`, optional 234 If set, this field must contain *at least* ``minLength`` number of 236 maxLength : `int`, optional 237 If set, this field must contain *no more than* ``maxLength`` number of 239 deprecated : None or `str`, optional 240 A description of why this Field is deprecated, including removal date. 241 If not None, the string is appended to the docstring for this Field. 255 def __init__(self, doc, dtype, default=None, optional=False,
256 listCheck=None, itemCheck=None,
257 length=None, minLength=None, maxLength=None,
259 if dtype
not in Field.supportedTypes:
260 raise ValueError(
"Unsupported dtype %s" % _typeStr(dtype))
261 if length
is not None:
263 raise ValueError(
"'length' (%d) must be positive" % length)
267 if maxLength
is not None and maxLength <= 0:
268 raise ValueError(
"'maxLength' (%d) must be positive" % maxLength)
269 if minLength
is not None and maxLength
is not None \
270 and minLength > maxLength:
271 raise ValueError(
"'maxLength' (%d) must be at least" 272 " as large as 'minLength' (%d)" % (maxLength, minLength))
274 if listCheck
is not None and not hasattr(listCheck,
"__call__"):
275 raise ValueError(
"'listCheck' must be callable")
276 if itemCheck
is not None and not hasattr(itemCheck,
"__call__"):
277 raise ValueError(
"'itemCheck' must be callable")
280 self.
_setup(doc=doc, dtype=List, default=default, check=
None, optional=optional, source=source,
281 deprecated=deprecated)
284 """Callable used to check the list as a whole. 288 """Callable used to validate individual items as they are inserted 293 """Data type of list items. 297 """Number of items that must be present in the list (or `None` to 298 disable checking the list's length). 302 """Minimum number of items that must be present in the list (or `None` 303 to disable checking the list's minimum length). 307 """Maximum number of items that must be present in the list (or `None` 308 to disable checking the list's maximum length). 312 """Validate the field. 316 instance : `lsst.pex.config.Config` 317 The config instance that contains this field. 321 lsst.pex.config.FieldValidationError 324 - The field is not optional, but the value is `None`. 325 - The list itself does not meet the requirements of the `length`, 326 `minLength`, or `maxLength` attributes. 327 - The `listCheck` callable returns `False`. 331 Individual item checks (`itemCheck`) are applied when each item is 332 set and are not re-checked by this method. 334 Field.validate(self, instance)
336 if value
is not None:
337 lenValue = len(value)
338 if self.
length is not None and not lenValue == self.
length:
339 msg =
"Required list length=%d, got length=%d" % (self.
length, lenValue)
342 msg =
"Minimum allowed list length=%d, got length=%d" % (self.
minLength, lenValue)
345 msg =
"Maximum allowed list length=%d, got length=%d" % (self.
maxLength, lenValue)
348 msg =
"%s is not a valid value" % str(value)
351 def __set__(self, instance, value, at=None, label="assignment"):
358 if value
is not None:
359 value =
List(instance, self, value, at, label)
361 history = instance._history.setdefault(self.name, [])
362 history.append((value, at, label))
364 instance._storage[self.name] = value
367 """Convert the value of this field to a plain `list`. 369 `lsst.pex.config.Config.toDict` is the primary user of this method. 373 instance : `lsst.pex.config.Config` 374 The config instance that contains this field. 379 Plain `list` of items, or `None` if the field is not set. 382 return list(value)
if value
is not None else None 384 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
385 """Compare two config instances for equality with respect to this 388 `lsst.pex.config.config.compare` is the primary user of this method. 392 instance1 : `lsst.pex.config.Config` 393 Left-hand-side `~lsst.pex.config.Config` instance in the 395 instance2 : `lsst.pex.config.Config` 396 Right-hand-side `~lsst.pex.config.Config` instance in the 399 If `True`, return as soon as an **inequality** is found. 401 Relative tolerance for floating point comparisons. 403 Absolute tolerance for floating point comparisons. 405 If not None, a callable that takes a `str`, used (possibly 406 repeatedly) to report inequalities. 411 `True` if the fields are equal; `False` otherwise. 415 Floating point comparisons are performed by `numpy.allclose`. 417 l1 = getattr(instance1, self.name)
418 l2 = getattr(instance2, self.name)
420 _joinNamePath(instance1._name, self.name),
421 _joinNamePath(instance2._name, self.name)
423 if not compareScalars(
"isnone for %s" % name, l1
is None, l2
is None, output=output):
425 if l1
is None and l2
is None:
427 if not compareScalars(
"size for %s" % name, len(l1), len(l2), output=output):
430 for n, v1, v2
in zip(range(len(l1)), l1, l2):
432 rtol=rtol, atol=atol, output=output)
433 if not result
and shortcut:
435 equal = equal
and result
def validate(self, instance)
def validateItem(self, i, x)
def __setitem__(self, i, x, at=None, label="setitem", setHistory=True)
def __init__(self, doc, dtype, default=None, optional=False, listCheck=None, itemCheck=None, length=None, minLength=None, maxLength=None, deprecated=None)
def __get__(self, instance, owner=None, at=None, label="default")
def insert(self, i, x, at=None, label="insert", setHistory=True)
def __init__(self, config, field, value, at, label, setHistory=True)
def __setattr__(self, attr, value, at=None, label="assignment")
def getStackFrame(relative=0)
def __delitem__(self, i, at=None, label="delitem", setHistory=True)
def toDict(self, instance)
def compareScalars(name, v1, v2, output, rtol=1E-8, atol=1E-8, dtype=None)
def _setup(self, doc, dtype, default, check, optional, source, deprecated)
def __set__(self, instance, value, at=None, label="assignment")
def __contains__(self, x)
def getComparisonName(name1, name2)