28__all__ = [
"ListField"]
33from typing
import Any, Generic, overload
35from .callStack
import getCallStack, getStackFrame
36from .comparison
import compareScalars, getComparisonName
42 UnexpectedProxyUsageError,
49class List(collections.abc.MutableSequence[FieldTypeVar]):
50 """List collection used internally by `ListField`.
55 Config instance that contains the ``field``.
57 Instance of the `ListField` using this ``List``.
59 Sequence of values that are inserted into this ``List``.
61 The call stack (created by `lsst.pex.config.callStack.getCallStack`).
63 Event label for the history.
64 setHistory : `bool`, optional
65 Enable setting the field
's history, using the value of the ``at``
66 parameter. Default is `
True`.
71 Raised
if an item
in the ``value`` parameter does
not have the
72 appropriate type
for this field
or does
not pass the
73 `ListField.itemCheck` method of the ``field`` parameter.
76 def __init__(self, config, field, value, at, label, setHistory=True):
84 for i, x
in enumerate(value):
85 self.
insert(i, x, setHistory=
False)
87 msg = f
"Value {value} is of incorrect type {_typeStr(value)}. Sequence type expected"
97 assert value
is not None
101 """Validate an item to determine if it can be included in the list.
106 Index of the item in the `list`.
113 Raised
if an item
in the ``value`` parameter does
not have the
114 appropriate type
for this field
or does
not pass the field
's
115 `ListField.itemCheck` method.
117 if not isinstance(x, self.
_field.itemtype)
and x
is not None:
118 msg =
"Item at position %d with value %s is of incorrect type %s. Expected %s" % (
122 _typeStr(self.
_field.itemtype),
126 if self.
_field.itemCheck
is not None and not self.
_field.itemCheck(x):
127 msg =
"Item at position %d is not a valid value: %s" % (i, x)
131 """Sequence of items contained by the `List` (`list`)."""
134 history = property(
lambda x: x._history)
135 """Read-only history.
139 return x
in self.
_list
142 return len(self.
_list)
146 self, i: int, x: FieldTypeVar, at: Any =
None, label: str =
"setitem", setHistory: bool =
True
154 x: Iterable[FieldTypeVar],
156 label: str =
"setitem",
157 setHistory: bool =
True,
161 def __setitem__(self, i, x, at=None, label="setitem", setHistory=True):
164 if isinstance(i, slice):
165 k, stop, step = i.indices(len(self))
166 for j, xj
in enumerate(x):
167 xj = _autocast(xj, self.
_field.itemtype)
172 x = _autocast(x, self.
_field.itemtype)
192 def __delitem__(self, i, at=None, label="delitem", setHistory=True):
202 return iter(self.
_list)
204 def insert(self, i, x, at=None, label="insert", setHistory=True):
205 """Insert an item into the list at the given index.
210 Index where the item is inserted.
212 Item that
is inserted.
214 The call stack (created by
215 `lsst.pex.config.callStack.getCallStack`).
216 label : `str`, optional
217 Event label
for the history.
218 setHistory : `bool`, optional
219 Enable setting the field
's history, using the value of the ``at``
220 parameter. Default is `
True`.
227 return repr(self.
_list)
230 return str(self.
_list)
234 if len(self) != len(other):
237 for i, j
in zip(self, other):
241 except AttributeError:
246 return not self.
__eq__(other)
249 if hasattr(getattr(self.
__class__, attr,
None),
"__set__"):
251 object.__setattr__(self, attr, value)
252 elif attr
in self.__dict__
or attr
in [
"_field",
"_config_",
"_history",
"_list",
"__doc__"]:
254 object.__setattr__(self, attr, value)
257 msg = f
"{_typeStr(self._field)} has no attribute {attr}"
262 f
"Proxy container for config field {self._field.name} cannot "
263 "be pickled; it should be converted to a built-in container before "
264 "being assigned to other objects or variables."
269 """A configuration field (`~lsst.pex.config.Field` subclass) that contains
270 a list of values of a specific type.
275 A description of the field.
276 dtype : class, optional
277 The data type of items
in the list. Optional
if supplied
as typing
278 argument to the
class.
279 default : sequence, optional
280 The default items
for the field.
281 optional : `bool`, optional
282 Set whether the field
is *optional*. When `
False`,
283 `lsst.pex.config.Config.validate` will fail
if the field
's value is
285 listCheck : callable, optional
286 A callable that validates the list
as a whole.
287 itemCheck : callable, optional
288 A callable that validates individual items
in the list.
289 length : `int`, optional
290 If set, this field must contain exactly ``length`` number of items.
291 minLength : `int`, optional
292 If set, this field must contain *at least* ``minLength`` number of
294 maxLength : `int`, optional
295 If set, this field must contain *no more than* ``maxLength`` number of
297 deprecated :
None or `str`, optional
298 A description of why this Field
is deprecated, including removal date.
299 If
not None, the string
is appended to the docstring
for this Field.
329 "dtype must either be supplied as an argument or as a type argument to the class"
331 if dtype
not in Field.supportedTypes:
332 raise ValueError(
"Unsupported dtype %s" % _typeStr(dtype))
333 if length
is not None:
335 raise ValueError(
"'length' (%d) must be positive" % length)
339 if maxLength
is not None and maxLength <= 0:
340 raise ValueError(
"'maxLength' (%d) must be positive" % maxLength)
341 if minLength
is not None and maxLength
is not None and minLength > maxLength:
343 "'maxLength' (%d) must be at least as large as 'minLength' (%d)" % (maxLength, minLength)
346 if listCheck
is not None and not hasattr(listCheck,
"__call__"):
347 raise ValueError(
"'listCheck' must be callable")
348 if itemCheck
is not None and not hasattr(itemCheck,
"__call__"):
349 raise ValueError(
"'itemCheck' must be callable")
351 source = getStackFrame()
359 deprecated=deprecated,
363 """Callable used to check the list as a whole.
367 """Callable used to validate individual items as they are inserted
372 """Data type of list items.
376 """Number of items that must be present in the list (or `None` to
377 disable checking the list's length).
381 """Minimum number of items that must be present in the list (or `None`
382 to disable checking the list's minimum length).
386 """Maximum number of items that must be present in the list (or `None`
387 to disable checking the list's maximum length).
391 """Validate the field.
396 The config instance that contains this field.
403 - The field
is not optional, but the value
is `
None`.
404 - The list itself does
not meet the requirements of the ``length``,
405 ``minLength``,
or ``maxLength`` attributes.
406 - The ``listCheck`` callable returns `
False`.
410 Individual item checks (``itemCheck``) are applied when each item
is
411 set
and are
not re-checked by this method.
413 Field.validate(self, instance)
415 if value
is not None:
416 lenValue = len(value)
417 if self.
length is not None and not lenValue == self.
length:
418 msg =
"Required list length=%d, got length=%d" % (self.
length, lenValue)
421 msg =
"Minimum allowed list length=%d, got length=%d" % (self.
minLength, lenValue)
424 msg =
"Maximum allowed list length=%d, got length=%d" % (self.
maxLength, lenValue)
427 msg =
"%s is not a valid value" % str(value)
433 value: Iterable[FieldTypeVar] |
None,
435 label: str =
"assignment",
443 if value
is not None:
444 value =
List(instance, self, value, at, label)
446 history = instance._history.setdefault(self.
namenamename, [])
447 history.append((value, at, label))
452 """Convert the value of this field to a plain `list`.
454 `lsst.pex.config.Config.toDict` is the primary user of this method.
459 The config instance that contains this field.
464 Plain `list` of items,
or `
None`
if the field
is not set.
467 return list(value)
if value
is not None else None
469 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
470 """Compare two config instances for equality with respect to this
473 `lsst.pex.config.config.compare` is the primary user of this method.
484 If `
True`,
return as soon
as an **inequality**
is found.
486 Relative tolerance
for floating point comparisons.
488 Absolute tolerance
for floating point comparisons.
490 If
not None, a callable that takes a `str`, used (possibly
491 repeatedly) to report inequalities.
496 `
True`
if the fields are equal; `
False` otherwise.
500 Floating point comparisons are performed by `numpy.allclose`.
504 name = getComparisonName(
507 if not compareScalars(
"isnone for %s" % name, l1
is None, l2
is None, output=output):
509 if l1
is None and l2
is None:
511 if not compareScalars(
"size for %s" % name, len(l1), len(l2), output=output):
514 for n, v1, v2
in zip(range(len(l1)), l1, l2):
515 result = compareScalars(
516 "%s[%d]" % (name, n), v1, v2, dtype=self.
dtype, rtol=rtol, atol=atol, output=output
518 if not result
and shortcut:
520 equal = equal
and result
__get__(self, instance, owner=None, at=None, label="default")
FieldTypeVar __get__(self, Config instance, Any owner=None, Any at=None, str label="default")
Field[FieldTypeVar] __get__(self, None instance, Any owner=None, Any at=None, str label="default")
_setup(self, doc, dtype, default, check, optional, source, deprecated)
_compare(self, instance1, instance2, shortcut, rtol, atol, output)
__init__(self, doc, dtype=None, default=None, optional=False, listCheck=None, itemCheck=None, length=None, minLength=None, maxLength=None, deprecated=None)
None __set__(self, Config instance, Iterable[FieldTypeVar]|None value, Any at=None, str label="assignment")
None __setitem__(self, slice i, Iterable[FieldTypeVar] x, Any at=None, str label="setitem", bool setHistory=True)
FieldTypeVar __getitem__(self, int i)
None __setitem__(self, int i, FieldTypeVar x, Any at=None, str label="setitem", bool setHistory=True)
insert(self, i, x, at=None, label="insert", setHistory=True)
__delitem__(self, i, at=None, label="delitem", setHistory=True)
__setattr__(self, attr, value, at=None, label="assignment")
__init__(self, config, field, value, at, label, setHistory=True)
__setitem__(self, i, x, at=None, label="setitem", setHistory=True)
daf::base::PropertyList * list