LSST Applications g00274db5b6+edbf708997,g00d0e8bbd7+edbf708997,g199a45376c+5137f08352,g1fd858c14a+1d4b6db739,g262e1987ae+f4d9505c4f,g29ae962dfc+7156fb1a53,g2cef7863aa+73c82f25e4,g35bb328faa+edbf708997,g3e17d7035e+5b3adc59f5,g3fd5ace14f+852fa6fbcb,g47891489e3+6dc8069a4c,g53246c7159+edbf708997,g64539dfbff+9f17e571f4,g67b6fd64d1+6dc8069a4c,g74acd417e5+ae494d68d9,g786e29fd12+af89c03590,g7ae74a0b1c+a25e60b391,g7aefaa3e3d+536efcc10a,g7cc15d900a+d121454f8d,g87389fa792+a4172ec7da,g89139ef638+6dc8069a4c,g8d7436a09f+28c28d8d6d,g8ea07a8fe4+db21c37724,g92c671f44c+9f17e571f4,g98df359435+b2e6376b13,g99af87f6a8+b0f4ad7b8d,gac66b60396+966efe6077,gb88ae4c679+7dec8f19df,gbaa8f7a6c5+38b34f4976,gbf99507273+edbf708997,gc24b5d6ed1+9f17e571f4,gca7fc764a6+6dc8069a4c,gcc769fe2a4+97d0256649,gd7ef33dd92+6dc8069a4c,gdab6d2f7ff+ae494d68d9,gdbb4c4dda9+9f17e571f4,ge410e46f29+6dc8069a4c,geaed405ab2+e194be0d2b,w.2025.47
LSST Data Management Base Package
Loading...
Searching...
No Matches
lsst.pex.config.listField.ListField Class Reference
Inheritance diagram for lsst.pex.config.listField.ListField:
lsst.pex.config.config.Field lsst.pex.config.listField.List

Public Member Functions

 __init__ (self, doc, dtype=None, default=None, optional=False, listCheck=None, itemCheck=None, length=None, minLength=None, maxLength=None, deprecated=None)
 
 validate (self, instance)
 
None __set__ (self, Config instance, Iterable[FieldTypeVar]|None value, Any at=None, str label="assignment")
 
 toDict (self, instance)
 
 __class_getitem__ (cls, tuple[type,...]|type|ForwardRef params)
 
 rename (self, instance)
 
 freeze (self, instance)
 
 save (self, outfile, instance)
 
Field[FieldTypeVar__get__ (self, None instance, Any owner=None, Any at=None, str label="default")
 
FieldTypeVar __get__ (self, Config instance, Any owner=None, Any at=None, str label="default")
 
 __get__ (self, instance, owner=None, at=None, label="default")
 
 __delete__ (self, instance, at=None, label="deletion")
 
 validateItem (self, i, x)
 
 list (self)
 
 __contains__ (self, x)
 
 __len__ (self)
 
None __setitem__ (self, int i, FieldTypeVar x, Any at=None, str label="setitem", bool setHistory=True)
 
None __setitem__ (self, slice i, Iterable[FieldTypeVar] x, Any at=None, str label="setitem", bool setHistory=True)
 
 __setitem__ (self, i, x, at=None, label="setitem", setHistory=True)
 
FieldTypeVar __getitem__ (self, int i)
 
MutableSequence[FieldTypeVar__getitem__ (self, slice i)
 
 __getitem__ (self, i)
 
 __delitem__ (self, i, at=None, label="delitem", setHistory=True)
 
 __iter__ (self)
 
 insert (self, i, x, at=None, label="insert", setHistory=True)
 
 __repr__ (self)
 
 __str__ (self)
 
 __eq__ (self, other)
 
 __ne__ (self, other)
 
 __setattr__ (self, attr, value, at=None, label="assignment")
 
 __reduce__ (self)
 

Public Attributes

 listCheck = listCheck
 
 itemCheck = itemCheck
 
 itemtype = dtype
 
 length = length
 
 minLength = minLength
 
 maxLength = maxLength
 
 dtype = dtype
 
 doc = doc
 
 deprecated = deprecated
 
 default = default
 
 check = check
 
 optional = optional
 
 source = source
 

Static Public Attributes

dict supportedTypes = {str, bool, float, int, complex}
 

Protected Member Functions

List[FieldTypeVar]|None _copy_storage (self, Config old, Config new)
 
 _compare (self, instance1, instance2, shortcut, rtol, atol, output)
 
 _setup (self, doc, dtype, default, check, optional, source, deprecated)
 
 _validateValue (self, value)
 
 _collectImports (self, instance, imports)
 
Config _config (self)
 
List _copy (self, Config config)
 

Static Protected Member Functions

Mapping[str, Any] _parseTypingArgs (tuple[type,...]|tuple[str,...] params, Mapping[str, Any] kwds)
 

Protected Attributes

 _field = field
 
 _config_ = weakref.ref(config)
 
Config _history = self._config._history.setdefault(self._field.name, [])
 
list _list = []
 
 _config
 

Properties

 history = property(lambda x: x._history)
 

Detailed Description

A configuration field (`~lsst.pex.config.Field` subclass) that contains
a list of values of a specific type.

Parameters
----------
doc : `str`
    A description of the field.
dtype : class, optional
    The data type of items in the list. Optional if supplied as typing
    argument to the class.
default : sequence, optional
    The default items for the field.
optional : `bool`, optional
    Set whether the field is *optional*. When `False`,
    `lsst.pex.config.Config.validate` will fail if the field's value is
    `None`.
listCheck : callable, optional
    A callable that validates the list as a whole.
itemCheck : callable, optional
    A callable that validates individual items in the list.
length : `int`, optional
    If set, this field must contain exactly ``length`` number of items.
minLength : `int`, optional
    If set, this field must contain *at least* ``minLength`` number of
    items.
maxLength : `int`, optional
    If set, this field must contain *no more than* ``maxLength`` number of
    items.
deprecated : None or `str`, optional
    A description of why this Field is deprecated, including removal date.
    If not None, the string is appended to the docstring for this Field.

See Also
--------
ChoiceField
ConfigChoiceField
ConfigDictField
ConfigField
ConfigurableField
DictField
Field
RangeField
RegistryField

Definition at line 278 of file listField.py.

Constructor & Destructor Documentation

◆ __init__()

lsst.pex.config.listField.ListField.__init__ ( self,
doc,
dtype = None,
default = None,
optional = False,
listCheck = None,
itemCheck = None,
length = None,
minLength = None,
maxLength = None,
deprecated = None )

Definition at line 324 of file listField.py.

336 ):
337 if dtype is None:
338 raise ValueError(
339 "dtype must either be supplied as an argument or as a type argument to the class"
340 )
341 if dtype not in Field.supportedTypes:
342 raise ValueError(f"Unsupported dtype {_typeStr(dtype)}")
343 if length is not None:
344 if length <= 0:
345 raise ValueError(f"'length' ({length}) must be positive")
346 minLength = None
347 maxLength = None
348 else:
349 if maxLength is not None and maxLength <= 0:
350 raise ValueError(f"'maxLength' ({maxLength}) must be positive")
351 if minLength is not None and maxLength is not None and minLength > maxLength:
352 raise ValueError(
353 f"'maxLength' ({maxLength}) must be at least as large as 'minLength' ({minLength})"
354 )
355
356 if listCheck is not None and not callable(listCheck):
357 raise ValueError("'listCheck' must be callable")
358 if itemCheck is not None and not callable(itemCheck):
359 raise ValueError("'itemCheck' must be callable")
360
361 source = getStackFrame()
362 self._setup(
363 doc=doc,
364 dtype=List,
365 default=default,
366 check=None,
367 optional=optional,
368 source=source,
369 deprecated=deprecated,
370 )
371
372 self.listCheck = listCheck
373 """Callable used to check the list as a whole.
374 """
375
376 self.itemCheck = itemCheck
377 """Callable used to validate individual items as they are inserted
378 into the list.
379 """
380
381 self.itemtype = dtype
382 """Data type of list items.
383 """
384
385 self.length = length
386 """Number of items that must be present in the list (or `None` to
387 disable checking the list's length).
388 """
389
390 self.minLength = minLength
391 """Minimum number of items that must be present in the list (or `None`
392 to disable checking the list's minimum length).
393 """
394
395 self.maxLength = maxLength
396 """Maximum number of items that must be present in the list (or `None`
397 to disable checking the list's maximum length).
398 """
399

Member Function Documentation

◆ __class_getitem__()

lsst.pex.config.config.Field.__class_getitem__ ( cls,
tuple[type, ...] | type | ForwardRef params )
inherited

Definition at line 464 of file config.py.

464 def __class_getitem__(cls, params: tuple[type, ...] | type | ForwardRef):
465 return _PexConfigGenericAlias(cls, params)
466

◆ __contains__()

lsst.pex.config.listField.List.__contains__ ( self,
x )
inherited

Definition at line 149 of file listField.py.

149 def __contains__(self, x):
150 return x in self._list
151

◆ __delete__()

lsst.pex.config.config.Field.__delete__ ( self,
instance,
at = None,
label = "deletion" )
inherited
Delete an attribute from a `lsst.pex.config.Config` instance.

Parameters
----------
instance : `lsst.pex.config.Config`
    The config instance that contains this field.
at : `list` of `lsst.pex.config.callStack.StackFrame`
    The call stack (created by
    `lsst.pex.config.callStack.getCallStack`).
label : `str`, optional
    Event label for the history.

Notes
-----
This is invoked by the owning `~lsst.pex.config.Config` object and
should not be called directly.

Definition at line 808 of file config.py.

808 def __delete__(self, instance, at=None, label="deletion"):
809 """Delete an attribute from a `lsst.pex.config.Config` instance.
810
811 Parameters
812 ----------
813 instance : `lsst.pex.config.Config`
814 The config instance that contains this field.
815 at : `list` of `lsst.pex.config.callStack.StackFrame`
816 The call stack (created by
817 `lsst.pex.config.callStack.getCallStack`).
818 label : `str`, optional
819 Event label for the history.
820
821 Notes
822 -----
823 This is invoked by the owning `~lsst.pex.config.Config` object and
824 should not be called directly.
825 """
826 if at is None:
827 at = getCallStack()
828 self.__set__(instance, None, at=at, label=label)
829

◆ __delitem__()

lsst.pex.config.listField.List.__delitem__ ( self,
i,
at = None,
label = "delitem",
setHistory = True )
inherited

Definition at line 199 of file listField.py.

199 def __delitem__(self, i, at=None, label="delitem", setHistory=True):
200 if self._config._frozen:
201 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")
202 del self._list[i]
203 if setHistory:
204 if at is None:
205 at = getCallStack()
206 self.history.append((list(self._list), at, label))
207

◆ __eq__()

lsst.pex.config.listField.List.__eq__ ( self,
other )
inherited

Definition at line 240 of file listField.py.

240 def __eq__(self, other):
241 if other is None:
242 return False
243 try:
244 if len(self) != len(other):
245 return False
246
247 for i, j in zip(self, other, strict=True):
248 if i != j:
249 return False
250 return True
251 except AttributeError:
252 # other is not a sequence type
253 return False
254

◆ __get__() [1/3]

FieldTypeVar lsst.pex.config.config.Field.__get__ ( self,
Config instance,
Any owner = None,
Any at = None,
str label = "default" )
inherited

Definition at line 717 of file config.py.

719 ) -> FieldTypeVar: ...
720

◆ __get__() [2/3]

lsst.pex.config.config.Field.__get__ ( self,
instance,
owner = None,
at = None,
label = "default" )
inherited
Define how attribute access should occur on the Config instance
This is invoked by the owning config object and should not be called
directly.

When the field attribute is accessed on a Config class object, it
returns the field object itself in order to allow inspection of
Config classes.

When the field attribute is access on a config instance, the actual
value described by the field (and held by the Config instance) is
returned.

Definition at line 721 of file config.py.

721 def __get__(self, instance, owner=None, at=None, label="default"):
722 """Define how attribute access should occur on the Config instance
723 This is invoked by the owning config object and should not be called
724 directly.
725
726 When the field attribute is accessed on a Config class object, it
727 returns the field object itself in order to allow inspection of
728 Config classes.
729
730 When the field attribute is access on a config instance, the actual
731 value described by the field (and held by the Config instance) is
732 returned.
733 """
734 if instance is None:
735 return self
736 else:
737 # try statements are almost free in python if they succeed
738 try:
739 return instance._storage[self.name]
740 except AttributeError:
741 if not isinstance(instance, Config):
742 return self
743 else:
744 raise AttributeError(
745 f"Config {instance} is missing _storage attribute, likely incorrectly initialized"
746 ) from None
747

◆ __get__() [3/3]

Field[FieldTypeVar] lsst.pex.config.config.Field.__get__ ( self,
None instance,
Any owner = None,
Any at = None,
str label = "default" )
inherited

Definition at line 712 of file config.py.

714 ) -> Field[FieldTypeVar]: ...
715

◆ __getitem__() [1/3]

lsst.pex.config.listField.List.__getitem__ ( self,
i )
inherited

Definition at line 196 of file listField.py.

196 def __getitem__(self, i):
197 return self._list[i]
198

◆ __getitem__() [2/3]

FieldTypeVar lsst.pex.config.listField.List.__getitem__ ( self,
int i )
inherited

Definition at line 191 of file listField.py.

191 def __getitem__(self, i: int) -> FieldTypeVar: ...
192

◆ __getitem__() [3/3]

MutableSequence[FieldTypeVar] lsst.pex.config.listField.List.__getitem__ ( self,
slice i )
inherited

Definition at line 194 of file listField.py.

194 def __getitem__(self, i: slice) -> MutableSequence[FieldTypeVar]: ...
195

◆ __iter__()

lsst.pex.config.listField.List.__iter__ ( self)
inherited

Definition at line 208 of file listField.py.

208 def __iter__(self):
209 return iter(self._list)
210

◆ __len__()

lsst.pex.config.listField.List.__len__ ( self)
inherited

Definition at line 152 of file listField.py.

152 def __len__(self):
153 return len(self._list)
154

◆ __ne__()

lsst.pex.config.listField.List.__ne__ ( self,
other )
inherited

Definition at line 255 of file listField.py.

255 def __ne__(self, other):
256 return not self.__eq__(other)
257

◆ __reduce__()

lsst.pex.config.listField.List.__reduce__ ( self)
inherited

Definition at line 270 of file listField.py.

270 def __reduce__(self):
271 raise UnexpectedProxyUsageError(
272 f"Proxy container for config field {self._field.name} cannot "
273 "be pickled; it should be converted to a built-in container before "
274 "being assigned to other objects or variables."
275 )
276
277

◆ __repr__()

lsst.pex.config.listField.List.__repr__ ( self)
inherited

Definition at line 234 of file listField.py.

234 def __repr__(self):
235 return repr(self._list)
236

◆ __set__()

None lsst.pex.config.listField.ListField.__set__ ( self,
Config instance,
Iterable[FieldTypeVar] | None value,
Any at = None,
str label = "assignment" )

Definition at line 440 of file listField.py.

446 ) -> None:
447 if instance._frozen:
448 raise FieldValidationError(self, instance, "Cannot modify a frozen Config")
449
450 if at is None:
451 at = getCallStack()
452
453 if value is not None:
454 value = List(instance, self, value, at, label)
455 else:
456 history = instance._history.setdefault(self.name, [])
457 history.append((value, at, label))
458
459 instance._storage[self.name] = value
460

◆ __setattr__()

lsst.pex.config.listField.List.__setattr__ ( self,
attr,
value,
at = None,
label = "assignment" )
inherited

Definition at line 258 of file listField.py.

258 def __setattr__(self, attr, value, at=None, label="assignment"):
259 if hasattr(getattr(self.__class__, attr, None), "__set__"):
260 # This allows properties to work.
261 object.__setattr__(self, attr, value)
262 elif attr in self.__dict__ or attr in ["_field", "_config_", "_history", "_list", "__doc__"]:
263 # This allows specific private attributes to work.
264 object.__setattr__(self, attr, value)
265 else:
266 # We throw everything else.
267 msg = f"{_typeStr(self._field)} has no attribute {attr}"
268 raise FieldValidationError(self._field, self._config, msg)
269

◆ __setitem__() [1/3]

lsst.pex.config.listField.List.__setitem__ ( self,
i,
x,
at = None,
label = "setitem",
setHistory = True )
inherited

Definition at line 170 of file listField.py.

170 def __setitem__(self, i, x, at=None, label="setitem", setHistory=True):
171 if self._config._frozen:
172 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")
173 if isinstance(i, slice):
174 k, stop, step = i.indices(len(self))
175 for j, xj in enumerate(x):
176 xj = _autocast(xj, self._field.itemtype)
177 self.validateItem(k, xj)
178 x[j] = xj
179 k += step
180 else:
181 x = _autocast(x, self._field.itemtype)
182 self.validateItem(i, x)
183
184 self._list[i] = x
185 if setHistory:
186 if at is None:
187 at = getCallStack()
188 self.history.append((list(self._list), at, label))
189

◆ __setitem__() [2/3]

None lsst.pex.config.listField.List.__setitem__ ( self,
int i,
FieldTypeVar x,
Any at = None,
str label = "setitem",
bool setHistory = True )
inherited

Definition at line 156 of file listField.py.

158 ) -> None: ...
159

◆ __setitem__() [3/3]

None lsst.pex.config.listField.List.__setitem__ ( self,
slice i,
Iterable[FieldTypeVar] x,
Any at = None,
str label = "setitem",
bool setHistory = True )
inherited

Definition at line 161 of file listField.py.

168 ) -> None: ...
169

◆ __str__()

lsst.pex.config.listField.List.__str__ ( self)
inherited

Definition at line 237 of file listField.py.

237 def __str__(self):
238 return str(self._list)
239

◆ _collectImports()

lsst.pex.config.config.Field._collectImports ( self,
instance,
imports )
protectedinherited
Call the _collectImports method on all config
objects the field may own, and union them with the supplied imports
set.

Parameters
----------
instance : instance or subclass of `lsst.pex.config.Config`
    A config object that has this field defined on it
imports : `set`
    Set of python modules that need imported after persistence

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField, lsst.pex.config.configDictField.ConfigDictField, lsst.pex.config.configField.ConfigField, lsst.pex.config.configurableActions._configurableActionStructField.ConfigurableActionStructField, and lsst.pex.config.configurableField.ConfigurableField.

Definition at line 626 of file config.py.

626 def _collectImports(self, instance, imports):
627 """Call the _collectImports method on all config
628 objects the field may own, and union them with the supplied imports
629 set.
630
631 Parameters
632 ----------
633 instance : instance or subclass of `lsst.pex.config.Config`
634 A config object that has this field defined on it
635 imports : `set`
636 Set of python modules that need imported after persistence
637 """
638 pass
639

◆ _compare()

lsst.pex.config.listField.ListField._compare ( self,
instance1,
instance2,
shortcut,
rtol,
atol,
output )
protected
Compare two config instances for equality with respect to this
field.

`lsst.pex.config.config.compare` is the primary user of this method.

Parameters
----------
instance1 : `lsst.pex.config.Config`
    Left-hand-side `~lsst.pex.config.Config` instance in the
    comparison.
instance2 : `lsst.pex.config.Config`
    Right-hand-side `~lsst.pex.config.Config` instance in the
    comparison.
shortcut : `bool`
    If `True`, return as soon as an **inequality** is found.
rtol : `float`
    Relative tolerance for floating point comparisons.
atol : `float`
    Absolute tolerance for floating point comparisons.
output : callable
    If not None, a callable that takes a `str`, used (possibly
    repeatedly) to report inequalities.

Returns
-------
equal : `bool`
    `True` if the fields are equal; `False` otherwise.

Notes
-----
Floating point comparisons are performed by `numpy.allclose`.

Reimplemented from lsst.pex.config.config.Field.

Definition at line 486 of file listField.py.

486 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
487 """Compare two config instances for equality with respect to this
488 field.
489
490 `lsst.pex.config.config.compare` is the primary user of this method.
491
492 Parameters
493 ----------
494 instance1 : `lsst.pex.config.Config`
495 Left-hand-side `~lsst.pex.config.Config` instance in the
496 comparison.
497 instance2 : `lsst.pex.config.Config`
498 Right-hand-side `~lsst.pex.config.Config` instance in the
499 comparison.
500 shortcut : `bool`
501 If `True`, return as soon as an **inequality** is found.
502 rtol : `float`
503 Relative tolerance for floating point comparisons.
504 atol : `float`
505 Absolute tolerance for floating point comparisons.
506 output : callable
507 If not None, a callable that takes a `str`, used (possibly
508 repeatedly) to report inequalities.
509
510 Returns
511 -------
512 equal : `bool`
513 `True` if the fields are equal; `False` otherwise.
514
515 Notes
516 -----
517 Floating point comparisons are performed by `numpy.allclose`.
518 """
519 l1 = getattr(instance1, self.name)
520 l2 = getattr(instance2, self.name)
521 name = getComparisonName(
522 _joinNamePath(instance1._name, self.name), _joinNamePath(instance2._name, self.name)
523 )
524 if l1 is None or l2 is None:
525 return compareScalars(name, l1, l2, output=output)
526 if not compareScalars(f"{name} (len)", len(l1), len(l2), output=output):
527 return False
528 equal = True
529 for n, v1, v2 in zip(range(len(l1)), l1, l2, strict=True):
530 result = compareScalars(
531 f"{name}[{n}]", v1, v2, dtype=self.dtype, rtol=rtol, atol=atol, output=output
532 )
533
534 if not result and shortcut:
535 return False
536 equal = equal and result
537 return equal

◆ _config()

Config lsst.pex.config.listField.List._config ( self)
protectedinherited

Definition at line 103 of file listField.py.

103 def _config(self) -> Config:
104 # Config Fields should never outlive their config class instance
105 # assert that as such here
106 value = self._config_()
107 assert value is not None
108 return value
109

◆ _copy()

List lsst.pex.config.listField.List._copy ( self,
Config config )
protectedinherited

Definition at line 146 of file listField.py.

146 def _copy(self, config: Config) -> List:
147 return type(self)(config, self._field, self._list.copy(), at=None, label="copy", setHistory=False)
148

◆ _copy_storage()

List[FieldTypeVar] | None lsst.pex.config.listField.ListField._copy_storage ( self,
Config old,
Config new )
protected
Copy the storage for this field in the given field into an object
suitable for storage in a new copy of that config.

Any frozen storage should be unfrozen.

Reimplemented from lsst.pex.config.config.Field.

Definition at line 479 of file listField.py.

479 def _copy_storage(self, old: Config, new: Config) -> List[FieldTypeVar] | None:
480 value: List[FieldTypeVar] | None = old._storage[self.name]
481 if value is not None:
482 return value._copy(new)
483 else:
484 return None
485

◆ _parseTypingArgs()

Mapping[str, Any] lsst.pex.config.config.Field._parseTypingArgs ( tuple[type, ...] | tuple[str, ...] params,
Mapping[str, Any] kwds )
staticprotectedinherited
Parse type annotations into keyword constructor arguments.

This is a special private method that interprets type arguments (i.e.
Field[str]) into keyword arguments to be passed on to the constructor.

Subclasses of Field can implement this method to customize how they
handle turning type parameters into keyword arguments (see DictField
for an example)

Parameters
----------
params : `tuple` of `type` or `tuple` of str
    Parameters passed to the type annotation. These will either be
    types or strings. Strings are to interpreted as forward references
    and will be treated as such.
kwds : `MutableMapping` with keys of `str` and values of `Any`
    These are the user supplied keywords that are to be passed to the
    Field constructor.

Returns
-------
kwds : `MutableMapping` with keys of `str` and values of `Any`
    The mapping of keywords that will be passed onto the constructor
    of the Field. Should be filled in with any information gleaned
    from the input parameters.

Raises
------
ValueError
    Raised if params is of incorrect length.
    Raised if a forward reference could not be resolved
    Raised if there is a conflict between params and values in kwds

Reimplemented in lsst.pex.config.configurableField.ConfigurableField, and lsst.pex.config.dictField.DictField.

Definition at line 410 of file config.py.

412 ) -> Mapping[str, Any]:
413 """Parse type annotations into keyword constructor arguments.
414
415 This is a special private method that interprets type arguments (i.e.
416 Field[str]) into keyword arguments to be passed on to the constructor.
417
418 Subclasses of Field can implement this method to customize how they
419 handle turning type parameters into keyword arguments (see DictField
420 for an example)
421
422 Parameters
423 ----------
424 params : `tuple` of `type` or `tuple` of str
425 Parameters passed to the type annotation. These will either be
426 types or strings. Strings are to interpreted as forward references
427 and will be treated as such.
428 kwds : `MutableMapping` with keys of `str` and values of `Any`
429 These are the user supplied keywords that are to be passed to the
430 Field constructor.
431
432 Returns
433 -------
434 kwds : `MutableMapping` with keys of `str` and values of `Any`
435 The mapping of keywords that will be passed onto the constructor
436 of the Field. Should be filled in with any information gleaned
437 from the input parameters.
438
439 Raises
440 ------
441 ValueError
442 Raised if params is of incorrect length.
443 Raised if a forward reference could not be resolved
444 Raised if there is a conflict between params and values in kwds
445 """
446 if len(params) > 1:
447 raise ValueError("Only single type parameters are supported")
448 unpackedParams = params[0]
449 if isinstance(unpackedParams, str):
450 _typ = ForwardRef(unpackedParams)
451 # type ignore below because typeshed seems to be wrong. It
452 # indicates there are only 2 args, as it was in python 3.8, but
453 # 3.9+ takes 3 args.
454 result = _typ._evaluate(globals(), locals(), recursive_guard=set()) # type: ignore
455 if result is None:
456 raise ValueError("Could not deduce type from input")
457 unpackedParams = cast(type, result)
458 if "dtype" in kwds and kwds["dtype"] != unpackedParams:
459 raise ValueError("Conflicting definition for dtype")
460 elif "dtype" not in kwds:
461 kwds = {**kwds, **{"dtype": unpackedParams}}
462 return kwds
463

◆ _setup()

lsst.pex.config.config.Field._setup ( self,
doc,
dtype,
default,
check,
optional,
source,
deprecated )
protectedinherited
Set attributes, usually during initialization.

Definition at line 486 of file config.py.

486 def _setup(self, doc, dtype, default, check, optional, source, deprecated):
487 """Set attributes, usually during initialization."""
488 self.dtype = dtype
489 """Data type for the field.
490 """
491
492 if not doc:
493 raise ValueError("Docstring is empty.")
494
495 # append the deprecation message to the docstring.
496 if deprecated is not None:
497 doc = f"{doc} Deprecated: {deprecated}"
498 self.doc = doc
499 """A description of the field (`str`).
500 """
501
502 self.deprecated = deprecated
503 """If not None, a description of why this field is deprecated (`str`).
504 """
505
506 self.__doc__ = f"{doc} (`{dtype.__name__}`"
507 if optional or default is not None:
508 self.__doc__ += f", default ``{default!r}``"
509 self.__doc__ += ")"
510
511 self.default = default
512 """Default value for this field.
513 """
514
515 self.check = check
516 """A user-defined function that validates the value of the field.
517 """
518
519 self.optional = optional
520 """Flag that determines if the field is required to be set (`bool`).
521
522 When `False`, `lsst.pex.config.Config.validate` will fail if the
523 field's value is `None`.
524 """
525
526 self.source = source
527 """The stack frame where this field is defined (`list` of
528 `~lsst.pex.config.callStack.StackFrame`).
529 """
530

◆ _validateValue()

lsst.pex.config.config.Field._validateValue ( self,
value )
protectedinherited
Validate a value.

Parameters
----------
value : object
    The value being validated.

Raises
------
TypeError
    Raised if the value's type is incompatible with the field's
    ``dtype``.
ValueError
    Raised if the value is rejected by the ``check`` method.

Reimplemented in lsst.pex.config.choiceField.ChoiceField, and lsst.pex.config.rangeField.RangeField.

Definition at line 598 of file config.py.

598 def _validateValue(self, value):
599 """Validate a value.
600
601 Parameters
602 ----------
603 value : object
604 The value being validated.
605
606 Raises
607 ------
608 TypeError
609 Raised if the value's type is incompatible with the field's
610 ``dtype``.
611 ValueError
612 Raised if the value is rejected by the ``check`` method.
613 """
614 if value is None:
615 return
616
617 if not isinstance(value, self.dtype):
618 msg = (
619 f"Value {value} is of incorrect type {_typeStr(value)}. Expected type {_typeStr(self.dtype)}"
620 )
621 raise TypeError(msg)
622 if self.check is not None and not self.check(value):
623 msg = f"Value {value} is not a valid value"
624 raise ValueError(msg)
625

◆ freeze()

lsst.pex.config.config.Field.freeze ( self,
instance )
inherited
Make this field read-only (for internal use only).

Parameters
----------
instance : `lsst.pex.config.Config`
    The config instance that contains this field.

Notes
-----
Freezing is only relevant for fields that hold subconfigs. Fields which
hold subconfigs should freeze each subconfig.

**Subclasses should implement this method.**

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField, lsst.pex.config.configDictField.ConfigDictField, lsst.pex.config.configField.ConfigField, lsst.pex.config.configurableActions._configurableActionStructField.ConfigurableActionStructField, and lsst.pex.config.configurableField.ConfigurableField.

Definition at line 581 of file config.py.

581 def freeze(self, instance):
582 """Make this field read-only (for internal use only).
583
584 Parameters
585 ----------
586 instance : `lsst.pex.config.Config`
587 The config instance that contains this field.
588
589 Notes
590 -----
591 Freezing is only relevant for fields that hold subconfigs. Fields which
592 hold subconfigs should freeze each subconfig.
593
594 **Subclasses should implement this method.**
595 """
596 pass
597

◆ insert()

lsst.pex.config.listField.List.insert ( self,
i,
x,
at = None,
label = "insert",
setHistory = True )
inherited
Insert an item into the list at the given index.

Parameters
----------
i : `int`
    Index where the item is inserted.
x : object
    Item that is inserted.
at : `list` of `~lsst.pex.config.callStack.StackFrame` or `None`,\
        optional
    The call stack (created by
    `lsst.pex.config.callStack.getCallStack`).
label : `str`, optional
    Event label for the history.
setHistory : `bool`, optional
    Enable setting the field's history, using the value of the ``at``
    parameter. Default is `True`.

Definition at line 211 of file listField.py.

211 def insert(self, i, x, at=None, label="insert", setHistory=True):
212 """Insert an item into the list at the given index.
213
214 Parameters
215 ----------
216 i : `int`
217 Index where the item is inserted.
218 x : object
219 Item that is inserted.
220 at : `list` of `~lsst.pex.config.callStack.StackFrame` or `None`,\
221 optional
222 The call stack (created by
223 `lsst.pex.config.callStack.getCallStack`).
224 label : `str`, optional
225 Event label for the history.
226 setHistory : `bool`, optional
227 Enable setting the field's history, using the value of the ``at``
228 parameter. Default is `True`.
229 """
230 if at is None:
231 at = getCallStack()
232 self.__setitem__(slice(i, i), [x], at=at, label=label, setHistory=setHistory)
233

◆ list()

lsst.pex.config.listField.List.list ( self)
inherited
Sequence of items contained by the `List` (`list`).

Definition at line 138 of file listField.py.

138 def list(self):
139 """Sequence of items contained by the `List` (`list`)."""
140 return self._list
141

◆ rename()

lsst.pex.config.config.Field.rename ( self,
instance )
inherited
Rename the field in a `~lsst.pex.config.Config` (for internal use
only).

Parameters
----------
instance : `lsst.pex.config.Config`
    The config instance that contains this field.

Notes
-----
This method is invoked by the `lsst.pex.config.Config` object that
contains this field and should not be called directly.

Renaming is only relevant for `~lsst.pex.config.Field` instances that
hold subconfigs. `~lsst.pex.config.Field`\s that hold subconfigs should
rename each subconfig with the full field name as generated by
`lsst.pex.config.config._joinNamePath`.

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField, lsst.pex.config.configDictField.ConfigDictField, lsst.pex.config.configField.ConfigField, lsst.pex.config.configurableActions._configurableActionStructField.ConfigurableActionStructField, and lsst.pex.config.configurableField.ConfigurableField.

Definition at line 531 of file config.py.

531 def rename(self, instance):
532 r"""Rename the field in a `~lsst.pex.config.Config` (for internal use
533 only).
534
535 Parameters
536 ----------
537 instance : `lsst.pex.config.Config`
538 The config instance that contains this field.
539
540 Notes
541 -----
542 This method is invoked by the `lsst.pex.config.Config` object that
543 contains this field and should not be called directly.
544
545 Renaming is only relevant for `~lsst.pex.config.Field` instances that
546 hold subconfigs. `~lsst.pex.config.Field`\s that hold subconfigs should
547 rename each subconfig with the full field name as generated by
548 `lsst.pex.config.config._joinNamePath`.
549 """
550 pass
551

◆ save()

lsst.pex.config.config.Field.save ( self,
outfile,
instance )
inherited
Save this field to a file (for internal use only).

Parameters
----------
outfile : file-like object
    A writeable field handle.
instance : `~lsst.pex.config.Config`
    The `~lsst.pex.config.Config` instance that contains this field.

Notes
-----
This method is invoked by the `~lsst.pex.config.Config` object that
contains this field and should not be called directly.

The output consists of the documentation string
(`lsst.pex.config.Field.doc`) formatted as a Python comment. The second
line is formatted as an assignment: ``{fullname}={value}``.

This output can be executed with Python.

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField, lsst.pex.config.configDictField.ConfigDictField, lsst.pex.config.configField.ConfigField, lsst.pex.config.configurableActions._configurableActionField.ConfigurableActionField, lsst.pex.config.configurableActions._configurableActionStructField.ConfigurableActionStructField, and lsst.pex.config.configurableField.ConfigurableField.

Definition at line 640 of file config.py.

640 def save(self, outfile, instance):
641 """Save this field to a file (for internal use only).
642
643 Parameters
644 ----------
645 outfile : file-like object
646 A writeable field handle.
647 instance : `~lsst.pex.config.Config`
648 The `~lsst.pex.config.Config` instance that contains this field.
649
650 Notes
651 -----
652 This method is invoked by the `~lsst.pex.config.Config` object that
653 contains this field and should not be called directly.
654
655 The output consists of the documentation string
656 (`lsst.pex.config.Field.doc`) formatted as a Python comment. The second
657 line is formatted as an assignment: ``{fullname}={value}``.
658
659 This output can be executed with Python.
660 """
661 value = self.__get__(instance)
662 fullname = _joinNamePath(instance._name, self.name)
663
664 if self.deprecated and value == self.default:
665 return
666
667 # write full documentation string as comment lines
668 # (i.e. first character is #)
669 doc = "# " + str(self.doc).replace("\n", "\n# ")
670 if isinstance(value, float) and not math.isfinite(value):
671 # non-finite numbers need special care
672 outfile.write(f"{doc}\n{fullname}=float('{value!r}')\n\n")
673 else:
674 outfile.write(f"{doc}\n{fullname}={value!r}\n\n")
675

◆ toDict()

lsst.pex.config.listField.ListField.toDict ( self,
instance )
Convert the value of this field to a plain `list`.

`lsst.pex.config.Config.toDict` is the primary user of this method.

Parameters
----------
instance : `lsst.pex.config.Config`
    The config instance that contains this field.

Returns
-------
`list`
    Plain `list` of items, or `None` if the field is not set.

Reimplemented from lsst.pex.config.config.Field.

Definition at line 461 of file listField.py.

461 def toDict(self, instance):
462 """Convert the value of this field to a plain `list`.
463
464 `lsst.pex.config.Config.toDict` is the primary user of this method.
465
466 Parameters
467 ----------
468 instance : `lsst.pex.config.Config`
469 The config instance that contains this field.
470
471 Returns
472 -------
473 `list`
474 Plain `list` of items, or `None` if the field is not set.
475 """
476 value = self.__get__(instance)
477 return list(value) if value is not None else None
478

◆ validate()

lsst.pex.config.listField.ListField.validate ( self,
instance )
Validate the field.

Parameters
----------
instance : `lsst.pex.config.Config`
    The config instance that contains this field.

Raises
------
lsst.pex.config.FieldValidationError
    Raised if:

    - The field is not optional, but the value is `None`.
    - The list itself does not meet the requirements of the ``length``,
      ``minLength``, or ``maxLength`` attributes.
    - The ``listCheck`` callable returns `False`.

Notes
-----
Individual item checks (``itemCheck``) are applied when each item is
set and are not re-checked by this method.

Reimplemented from lsst.pex.config.config.Field.

Definition at line 400 of file listField.py.

400 def validate(self, instance):
401 """Validate the field.
402
403 Parameters
404 ----------
405 instance : `lsst.pex.config.Config`
406 The config instance that contains this field.
407
408 Raises
409 ------
410 lsst.pex.config.FieldValidationError
411 Raised if:
412
413 - The field is not optional, but the value is `None`.
414 - The list itself does not meet the requirements of the ``length``,
415 ``minLength``, or ``maxLength`` attributes.
416 - The ``listCheck`` callable returns `False`.
417
418 Notes
419 -----
420 Individual item checks (``itemCheck``) are applied when each item is
421 set and are not re-checked by this method.
422 """
423 Field.validate(self, instance)
424 value = self.__get__(instance)
425 if value is not None:
426 lenValue = len(value)
427 if self.length is not None and not lenValue == self.length:
428 msg = f"Required list length={self.length}, got length={lenValue}"
429 raise FieldValidationError(self, instance, msg)
430 elif self.minLength is not None and lenValue < self.minLength:
431 msg = f"Minimum allowed list length={self.minLength}, got length={lenValue}"
432 raise FieldValidationError(self, instance, msg)
433 elif self.maxLength is not None and lenValue > self.maxLength:
434 msg = f"Maximum allowed list length={self.maxLength}, got length={lenValue}"
435 raise FieldValidationError(self, instance, msg)
436 elif self.listCheck is not None and not self.listCheck(value):
437 msg = f"{value} is not a valid value"
438 raise FieldValidationError(self, instance, msg)
439

◆ validateItem()

lsst.pex.config.listField.List.validateItem ( self,
i,
x )
inherited
Validate an item to determine if it can be included in the list.

Parameters
----------
i : `int`
    Index of the item in the `list`.
x : object
    Item in the `list`.

Raises
------
FieldValidationError
    Raised if an item in the ``value`` parameter does not have the
    appropriate type for this field or does not pass the field's
    `ListField.itemCheck` method.

Definition at line 110 of file listField.py.

110 def validateItem(self, i, x):
111 """Validate an item to determine if it can be included in the list.
112
113 Parameters
114 ----------
115 i : `int`
116 Index of the item in the `list`.
117 x : object
118 Item in the `list`.
119
120 Raises
121 ------
122 FieldValidationError
123 Raised if an item in the ``value`` parameter does not have the
124 appropriate type for this field or does not pass the field's
125 `ListField.itemCheck` method.
126 """
127 if not isinstance(x, self._field.itemtype) and x is not None:
128 msg = (
129 f"Item at position {i} with value {x} is of incorrect type {_typeStr(x)}. "
130 f"Expected {_typeStr(self._field.itemtype)}"
131 )
132 raise FieldValidationError(self._field, self._config, msg)
133
134 if self._field.itemCheck is not None and not self._field.itemCheck(x):
135 msg = f"Item at position {i} is not a valid value: {x}"
136 raise FieldValidationError(self._field, self._config, msg)
137

Member Data Documentation

◆ _config

lsst.pex.config.listField.List._config
protectedinherited

Definition at line 132 of file listField.py.

◆ _config_

lsst.pex.config.listField.List._config_ = weakref.ref(config)
protectedinherited

Definition at line 88 of file listField.py.

◆ _field

lsst.pex.config.listField.List._field = field
protectedinherited

Definition at line 87 of file listField.py.

◆ _history

Config lsst.pex.config.listField.List._history = self._config._history.setdefault(self._field.name, [])
protectedinherited

Definition at line 89 of file listField.py.

◆ _list

lsst.pex.config.listField.List._list = []
protectedinherited

Definition at line 90 of file listField.py.

◆ check

lsst.pex.config.config.Field.check = check
inherited

Definition at line 515 of file config.py.

◆ default

lsst.pex.config.config.Field.default = default
inherited

Definition at line 511 of file config.py.

◆ deprecated

lsst.pex.config.config.Field.deprecated = deprecated
inherited

Definition at line 502 of file config.py.

◆ doc

lsst.pex.config.config.Field.doc = doc
inherited

Definition at line 498 of file config.py.

◆ dtype

lsst.pex.config.config.Field.dtype = dtype
inherited

Definition at line 488 of file config.py.

◆ itemCheck

lsst.pex.config.listField.ListField.itemCheck = itemCheck

Definition at line 376 of file listField.py.

◆ itemtype

lsst.pex.config.listField.ListField.itemtype = dtype

Definition at line 381 of file listField.py.

◆ length

lsst.pex.config.listField.ListField.length = length

Definition at line 385 of file listField.py.

◆ listCheck

lsst.pex.config.listField.ListField.listCheck = listCheck

Definition at line 372 of file listField.py.

◆ maxLength

lsst.pex.config.listField.ListField.maxLength = maxLength

Definition at line 395 of file listField.py.

◆ minLength

lsst.pex.config.listField.ListField.minLength = minLength

Definition at line 390 of file listField.py.

◆ optional

lsst.pex.config.config.Field.optional = optional
inherited

Definition at line 519 of file config.py.

◆ source

lsst.pex.config.config.Field.source = source
inherited

Definition at line 526 of file config.py.

◆ supportedTypes

dict lsst.pex.config.config.Field.supportedTypes = {str, bool, float, int, complex}
staticinherited

Definition at line 405 of file config.py.

Property Documentation

◆ history

lsst.pex.config.listField.List.history = property(lambda x: x._history)
staticinherited

Definition at line 142 of file listField.py.


The documentation for this class was generated from the following file: