LSST Applications 29.1.0,g0fba68d861+6b120c4394,g123d84c11c+8c5ae1fdc5,g1ec0fe41b4+191117f6ec,g1fd858c14a+c8450ae71a,g3533f9d6cb+a04f9ee0ab,g35bb328faa+8c5ae1fdc5,g3f0dcc2b1b+7df08700bd,g4178042926+b4254969db,g44ba364a48+04455b336b,g53246c7159+8c5ae1fdc5,g60b5630c4e+a04f9ee0ab,g663da51e9b+b05e6e1875,g67b6fd64d1+250bf6acd3,g78460c75b0+7e33a9eb6d,g786e29fd12+668abc6043,g8352419a5c+8c5ae1fdc5,g87e3079a85+d3fa38de54,g8852436030+cd899e2626,g89139ef638+250bf6acd3,g93a033419f+31ead11197,g989de1cb63+250bf6acd3,g9f33ca652e+f6053ecf14,ga1e959baac+5fbc491aed,ga2f891cd6c+a04f9ee0ab,gabe3b4be73+8856018cbb,gabf8522325+1f7e6d67b9,gac2eed3f23+250bf6acd3,gb1101e3267+0c331e9486,gb89ab40317+250bf6acd3,gcf25f946ba+cd899e2626,gd107969129+8964d67276,gd6cbbdb0b4+6bbecc8878,gde0f65d7ad+d65f9e019a,ge278dab8ac+eb3bbeb12f,ge410e46f29+250bf6acd3,gf5e32f922b+8c5ae1fdc5,gff02db199a+747430a128,gffe7e49bb4+a04f9ee0ab
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

 _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)
 

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 265 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 311 of file listField.py.

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

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 136 of file listField.py.

136 def __contains__(self, x):
137 return x in self._list
138

◆ __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 800 of file config.py.

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

◆ __delitem__()

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

Definition at line 186 of file listField.py.

186 def __delitem__(self, i, at=None, label="delitem", setHistory=True):
187 if self._config._frozen:
188 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")
189 del self._list[i]
190 if setHistory:
191 if at is None:
192 at = getCallStack()
193 self.history.append((list(self._list), at, label))
194

◆ __eq__()

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

Definition at line 227 of file listField.py.

227 def __eq__(self, other):
228 if other is None:
229 return False
230 try:
231 if len(self) != len(other):
232 return False
233
234 for i, j in zip(self, other, strict=True):
235 if i != j:
236 return False
237 return True
238 except AttributeError:
239 # other is not a sequence type
240 return False
241

◆ __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 709 of file config.py.

711 ) -> FieldTypeVar: ...
712

◆ __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 713 of file config.py.

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

◆ __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 704 of file config.py.

706 ) -> Field[FieldTypeVar]: ...
707

◆ __getitem__() [1/3]

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

Definition at line 183 of file listField.py.

183 def __getitem__(self, i):
184 return self._list[i]
185

◆ __getitem__() [2/3]

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

Definition at line 178 of file listField.py.

178 def __getitem__(self, i: int) -> FieldTypeVar: ...
179

◆ __getitem__() [3/3]

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

Definition at line 181 of file listField.py.

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

◆ __iter__()

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

Definition at line 195 of file listField.py.

195 def __iter__(self):
196 return iter(self._list)
197

◆ __len__()

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

Definition at line 139 of file listField.py.

139 def __len__(self):
140 return len(self._list)
141

◆ __ne__()

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

Definition at line 242 of file listField.py.

242 def __ne__(self, other):
243 return not self.__eq__(other)
244

◆ __reduce__()

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

Definition at line 257 of file listField.py.

257 def __reduce__(self):
258 raise UnexpectedProxyUsageError(
259 f"Proxy container for config field {self._field.name} cannot "
260 "be pickled; it should be converted to a built-in container before "
261 "being assigned to other objects or variables."
262 )
263
264

◆ __repr__()

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

Definition at line 221 of file listField.py.

221 def __repr__(self):
222 return repr(self._list)
223

◆ __set__()

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

Definition at line 427 of file listField.py.

433 ) -> None:
434 if instance._frozen:
435 raise FieldValidationError(self, instance, "Cannot modify a frozen Config")
436
437 if at is None:
438 at = getCallStack()
439
440 if value is not None:
441 value = List(instance, self, value, at, label)
442 else:
443 history = instance._history.setdefault(self.name, [])
444 history.append((value, at, label))
445
446 instance._storage[self.name] = value
447

◆ __setattr__()

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

Definition at line 245 of file listField.py.

245 def __setattr__(self, attr, value, at=None, label="assignment"):
246 if hasattr(getattr(self.__class__, attr, None), "__set__"):
247 # This allows properties to work.
248 object.__setattr__(self, attr, value)
249 elif attr in self.__dict__ or attr in ["_field", "_config_", "_history", "_list", "__doc__"]:
250 # This allows specific private attributes to work.
251 object.__setattr__(self, attr, value)
252 else:
253 # We throw everything else.
254 msg = f"{_typeStr(self._field)} has no attribute {attr}"
255 raise FieldValidationError(self._field, self._config, msg)
256

◆ __setitem__() [1/3]

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

Definition at line 157 of file listField.py.

157 def __setitem__(self, i, x, at=None, label="setitem", setHistory=True):
158 if self._config._frozen:
159 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")
160 if isinstance(i, slice):
161 k, stop, step = i.indices(len(self))
162 for j, xj in enumerate(x):
163 xj = _autocast(xj, self._field.itemtype)
164 self.validateItem(k, xj)
165 x[j] = xj
166 k += step
167 else:
168 x = _autocast(x, self._field.itemtype)
169 self.validateItem(i, x)
170
171 self._list[i] = x
172 if setHistory:
173 if at is None:
174 at = getCallStack()
175 self.history.append((list(self._list), at, label))
176

◆ __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 143 of file listField.py.

145 ) -> None: ...
146

◆ __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 148 of file listField.py.

155 ) -> None: ...
156

◆ __str__()

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

Definition at line 224 of file listField.py.

224 def __str__(self):
225 return str(self._list)
226

◆ _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 466 of file listField.py.

466 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
467 """Compare two config instances for equality with respect to this
468 field.
469
470 `lsst.pex.config.config.compare` is the primary user of this method.
471
472 Parameters
473 ----------
474 instance1 : `lsst.pex.config.Config`
475 Left-hand-side `~lsst.pex.config.Config` instance in the
476 comparison.
477 instance2 : `lsst.pex.config.Config`
478 Right-hand-side `~lsst.pex.config.Config` instance in the
479 comparison.
480 shortcut : `bool`
481 If `True`, return as soon as an **inequality** is found.
482 rtol : `float`
483 Relative tolerance for floating point comparisons.
484 atol : `float`
485 Absolute tolerance for floating point comparisons.
486 output : callable
487 If not None, a callable that takes a `str`, used (possibly
488 repeatedly) to report inequalities.
489
490 Returns
491 -------
492 equal : `bool`
493 `True` if the fields are equal; `False` otherwise.
494
495 Notes
496 -----
497 Floating point comparisons are performed by `numpy.allclose`.
498 """
499 l1 = getattr(instance1, self.name)
500 l2 = getattr(instance2, self.name)
501 name = getComparisonName(
502 _joinNamePath(instance1._name, self.name), _joinNamePath(instance2._name, self.name)
503 )
504 if l1 is None or l2 is None:
505 return compareScalars(name, l1, l2, output=output)
506 if not compareScalars(f"{name} (len)", len(l1), len(l2), output=output):
507 return False
508 equal = True
509 for n, v1, v2 in zip(range(len(l1)), l1, l2, strict=True):
510 result = compareScalars(
511 f"{name}[{n}]", v1, v2, dtype=self.dtype, rtol=rtol, atol=atol, output=output
512 )
513
514 if not result and shortcut:
515 return False
516 equal = equal and result
517 return equal

◆ _config()

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

Definition at line 93 of file listField.py.

93 def _config(self) -> Config:
94 # Config Fields should never outlive their config class instance
95 # assert that as such here
96 value = self._config_()
97 assert value is not None
98 return value
99

◆ _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 198 of file listField.py.

198 def insert(self, i, x, at=None, label="insert", setHistory=True):
199 """Insert an item into the list at the given index.
200
201 Parameters
202 ----------
203 i : `int`
204 Index where the item is inserted.
205 x : object
206 Item that is inserted.
207 at : `list` of `~lsst.pex.config.callStack.StackFrame` or `None`,\
208 optional
209 The call stack (created by
210 `lsst.pex.config.callStack.getCallStack`).
211 label : `str`, optional
212 Event label for the history.
213 setHistory : `bool`, optional
214 Enable setting the field's history, using the value of the ``at``
215 parameter. Default is `True`.
216 """
217 if at is None:
218 at = getCallStack()
219 self.__setitem__(slice(i, i), [x], at=at, label=label, setHistory=setHistory)
220

◆ list()

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

Definition at line 128 of file listField.py.

128 def list(self):
129 """Sequence of items contained by the `List` (`list`)."""
130 return self._list
131

◆ 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 448 of file listField.py.

448 def toDict(self, instance):
449 """Convert the value of this field to a plain `list`.
450
451 `lsst.pex.config.Config.toDict` is the primary user of this method.
452
453 Parameters
454 ----------
455 instance : `lsst.pex.config.Config`
456 The config instance that contains this field.
457
458 Returns
459 -------
460 `list`
461 Plain `list` of items, or `None` if the field is not set.
462 """
463 value = self.__get__(instance)
464 return list(value) if value is not None else None
465

◆ 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 387 of file listField.py.

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

◆ 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 100 of file listField.py.

100 def validateItem(self, i, x):
101 """Validate an item to determine if it can be included in the list.
102
103 Parameters
104 ----------
105 i : `int`
106 Index of the item in the `list`.
107 x : object
108 Item in the `list`.
109
110 Raises
111 ------
112 FieldValidationError
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.
116 """
117 if not isinstance(x, self._field.itemtype) and x is not None:
118 msg = (
119 f"Item at position {i} with value {x} is of incorrect type {_typeStr(x)}. "
120 f"Expected {_typeStr(self._field.itemtype)}"
121 )
122 raise FieldValidationError(self._field, self._config, msg)
123
124 if self._field.itemCheck is not None and not self._field.itemCheck(x):
125 msg = f"Item at position {i} is not a valid value: {x}"
126 raise FieldValidationError(self._field, self._config, msg)
127

Member Data Documentation

◆ _config

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

Definition at line 122 of file listField.py.

◆ _config_

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

Definition at line 78 of file listField.py.

◆ _field

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

Definition at line 77 of file listField.py.

◆ _history

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

Definition at line 79 of file listField.py.

◆ _list

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

Definition at line 80 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 363 of file listField.py.

◆ itemtype

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

Definition at line 368 of file listField.py.

◆ length

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

Definition at line 372 of file listField.py.

◆ listCheck

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

Definition at line 359 of file listField.py.

◆ maxLength

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

Definition at line 382 of file listField.py.

◆ minLength

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

Definition at line 377 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 132 of file listField.py.


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