LSST Applications 28.0.2,g0fba68d861+5b923b673a,g1fd858c14a+7a7b9dd5ed,g2c84ff76c0+5548bfee71,g30358e5240+f0e04ebe90,g35bb328faa+fcb1d3bbc8,g436fd98eb5+bdc6fcdd04,g4af146b050+742274f7cd,g4d2262a081+3efd3f8190,g4e0f332c67+cb09b8a5b6,g53246c7159+fcb1d3bbc8,g5a012ec0e7+477f9c599b,g5edb6fd927+826dfcb47f,g60b5630c4e+bdc6fcdd04,g67b6fd64d1+2218407a0c,g78460c75b0+2f9a1b4bcd,g786e29fd12+cf7ec2a62a,g7b71ed6315+fcb1d3bbc8,g87b7deb4dc+f9ac2ab1bd,g8852436030+ebf28f0d95,g89139ef638+2218407a0c,g9125e01d80+fcb1d3bbc8,g989de1cb63+2218407a0c,g9f33ca652e+42fb53f4c8,g9f7030ddb1+11b9b6f027,ga2b97cdc51+bdc6fcdd04,gab72ac2889+bdc6fcdd04,gabe3b4be73+1e0a283bba,gabf8522325+3210f02652,gb1101e3267+9c79701da9,gb58c049af0+f03b321e39,gb89ab40317+2218407a0c,gcf25f946ba+ebf28f0d95,gd6cbbdb0b4+e8f9c9c900,gd9a9a58781+fcb1d3bbc8,gde0f65d7ad+a08f294619,ge278dab8ac+3ef3db156b,ge410e46f29+2218407a0c,gf67bdafdda+2218407a0c
LSST Data Management Base Package
Loading...
Searching...
No Matches
lsst.pex.config.dictField.DictField Class Reference
Inheritance diagram for lsst.pex.config.dictField.DictField:
lsst.pex.config.config.Field lsst.pex.config.dictField.Dict lsst.pex.config.configDictField.ConfigDictField

Public Member Functions

 __init__ (self, doc, keytype=None, itemtype=None, default=None, optional=False, dictCheck=None, keyCheck=None, itemCheck=None, deprecated=None)
 
 validate (self, instance)
 
None __set__ (self, Config instance, Mapping[KeyTypeVar, ItemTypeVar]|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")
 
ItemTypeVar __getitem__ (self, KeyTypeVar k)
 
int __len__ (self)
 
Iterator[KeyTypeVar__iter__ (self)
 
bool __contains__ (self, Any k)
 
None __setitem__ (self, KeyTypeVar k, ItemTypeVar x, Any at=None, str label="setitem", bool setHistory=True)
 
None __delitem__ (self, KeyTypeVar k, Any at=None, str label="delitem", bool setHistory=True)
 
 __repr__ (self)
 
 __str__ (self)
 
 __setattr__ (self, attr, value, at=None, label="assignment")
 
 __reduce__ (self)
 

Public Attributes

 keytype = keytype
 
 itemtype = itemtype
 
 dictCheck = dictCheck
 
 keyCheck = keyCheck
 
 itemCheck = itemCheck
 
 dtype = dtype
 
 doc = doc
 
 deprecated = deprecated
 
 default = default
 
 check = check
 
 optional = optional
 
 source = source
 

Static Public Attributes

type DictClass = Dict
 
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)
 
dict _dict = {}
 
Config _history = self._config._history.setdefault(self._field.name, [])
 
 _config
 

Properties

 history = property(lambda x: x._history)
 

Detailed Description

A configuration field (`~lsst.pex.config.Field` subclass) that maps keys
and values.

The types of both items and keys are restricted to these builtin types:
`int`, `float`, `complex`, `bool`, and `str`). All keys share the same type
and all values share the same type. Keys can have a different type from
values.

Parameters
----------
doc : `str`
    A documentation string that describes the configuration field.
keytype : {`int`, `float`, `complex`, `bool`, `str`}, optional
    The type of the mapping keys. All keys must have this type. Optional
    if keytype and itemtype are supplied as typing arguments to the class.
itemtype : {`int`, `float`, `complex`, `bool`, `str`}, optional
    Type of the mapping values. Optional if keytype and itemtype are
    supplied as typing arguments to the class.
default : `dict`, optional
    The default mapping.
optional : `bool`, optional
    If `True`, the field doesn't need to have a set value.
dictCheck : callable
    A function that validates the dictionary as a whole.
keyCheck : callable
    A function that validates individual mapping keys.
itemCheck : callable
    A function that validates individual mapping values.
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
Field
ListField
RangeField
RegistryField

Examples
--------
This field maps has `str` keys and `int` values:

>>> from lsst.pex.config import Config, DictField
>>> class MyConfig(Config):
...     field = DictField(
...         doc="Example string-to-int mapping field.",
...         keytype=str,
...         itemtype=int,
...         default={},
...     )
>>> config = MyConfig()
>>> config.field["myKey"] = 42
>>> print(config.field)
{'myKey': 42}

Definition at line 197 of file dictField.py.

Constructor & Destructor Documentation

◆ __init__()

lsst.pex.config.dictField.DictField.__init__ ( self,
doc,
keytype = None,
itemtype = None,
default = None,
optional = False,
dictCheck = None,
keyCheck = None,
itemCheck = None,
deprecated = None )

Definition at line 292 of file dictField.py.

303 ):
304 source = getStackFrame()
305 self._setup(
306 doc=doc,
307 dtype=Dict,
308 default=default,
309 check=None,
310 optional=optional,
311 source=source,
312 deprecated=deprecated,
313 )
314 if keytype is None:
315 raise ValueError(
316 "keytype must either be supplied as an argument or as a type argument to the class"
317 )
318 if keytype not in self.supportedTypes:
319 raise ValueError(f"'keytype' {_typeStr(keytype)} is not a supported type")
320 elif itemtype is not None and itemtype not in self.supportedTypes:
321 raise ValueError(f"'itemtype' {_typeStr(itemtype)} is not a supported type")
322
323 check_errors = []
324 for name, check in (("dictCheck", dictCheck), ("keyCheck", keyCheck), ("itemCheck", itemCheck)):
325 if check is not None and not callable(check):
326 check_errors.append(name)
327 if check_errors:
328 raise ValueError(f"{', '.join(check_errors)} must be callable")
329
330 self.keytype = keytype
331 self.itemtype = itemtype
332 self.dictCheck = dictCheck
333 self.keyCheck = keyCheck
334 self.itemCheck = itemCheck
335

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__()

bool lsst.pex.config.dictField.Dict.__contains__ ( self,
Any k )
inherited

Definition at line 112 of file dictField.py.

112 def __contains__(self, k: Any) -> bool:
113 return k in self._dict
114

◆ __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__()

None lsst.pex.config.dictField.Dict.__delitem__ ( self,
KeyTypeVar k,
Any at = None,
str label = "delitem",
bool setHistory = True )
inherited

Definition at line 159 of file dictField.py.

161 ) -> None:
162 if self._config._frozen:
163 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")
164
165 del self._dict[k]
166 if setHistory:
167 if at is None:
168 at = getCallStack()
169 self._history.append((dict(self._dict), at, label))
170

◆ __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__()

ItemTypeVar lsst.pex.config.dictField.Dict.__getitem__ ( self,
KeyTypeVar k )
inherited

Definition at line 103 of file dictField.py.

103 def __getitem__(self, k: KeyTypeVar) -> ItemTypeVar:
104 return self._dict[k]
105

◆ __iter__()

Iterator[KeyTypeVar] lsst.pex.config.dictField.Dict.__iter__ ( self)
inherited

Definition at line 109 of file dictField.py.

109 def __iter__(self) -> Iterator[KeyTypeVar]:
110 return iter(self._dict)
111

◆ __len__()

int lsst.pex.config.dictField.Dict.__len__ ( self)
inherited

Definition at line 106 of file dictField.py.

106 def __len__(self) -> int:
107 return len(self._dict)
108

◆ __reduce__()

lsst.pex.config.dictField.Dict.__reduce__ ( self)
inherited

Definition at line 189 of file dictField.py.

189 def __reduce__(self):
190 raise UnexpectedProxyUsageError(
191 f"Proxy container for config field {self._field.name} cannot "
192 "be pickled; it should be converted to a built-in container before "
193 "being assigned to other objects or variables."
194 )
195
196

◆ __repr__()

lsst.pex.config.dictField.Dict.__repr__ ( self)
inherited

Definition at line 171 of file dictField.py.

171 def __repr__(self):
172 return repr(self._dict)
173

◆ __set__()

None lsst.pex.config.dictField.DictField.__set__ ( self,
Config instance,
Mapping[KeyTypeVar, ItemTypeVar] | None value,
Any at = None,
str label = "assignment" )

Definition at line 367 of file dictField.py.

373 ) -> None:
374 if instance._frozen:
375 msg = f"Cannot modify a frozen Config. Attempting to set field to value {value}"
376 raise FieldValidationError(self, instance, msg)
377
378 if at is None:
379 at = getCallStack()
380 if value is not None:
381 value = self.DictClass(instance, self, value, at=at, label=label)
382 else:
383 history = instance._history.setdefault(self.name, [])
384 history.append((value, at, label))
385
386 instance._storage[self.name] = value
387

◆ __setattr__()

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

Definition at line 177 of file dictField.py.

177 def __setattr__(self, attr, value, at=None, label="assignment"):
178 if hasattr(getattr(self.__class__, attr, None), "__set__"):
179 # This allows properties to work.
180 object.__setattr__(self, attr, value)
181 elif attr in self.__dict__ or attr in ["_field", "_config_", "_history", "_dict", "__doc__"]:
182 # This allows specific private attributes to work.
183 object.__setattr__(self, attr, value)
184 else:
185 # We throw everything else.
186 msg = f"{_typeStr(self._field)} has no attribute {attr}"
187 raise FieldValidationError(self._field, self._config, msg)
188

◆ __setitem__()

None lsst.pex.config.dictField.Dict.__setitem__ ( self,
KeyTypeVar k,
ItemTypeVar x,
Any at = None,
str label = "setitem",
bool setHistory = True )
inherited

Definition at line 115 of file dictField.py.

117 ) -> None:
118 if self._config._frozen:
119 msg = f"Cannot modify a frozen Config. Attempting to set item at key {k!r} to value {x}"
120 raise FieldValidationError(self._field, self._config, msg)
121
122 # validate keytype
123 k = _autocast(k, self._field.keytype)
124 if type(k) is not self._field.keytype:
125 msg = f"Key {k!r} is of type {_typeStr(k)}, expected type {_typeStr(self._field.keytype)}"
126 raise FieldValidationError(self._field, self._config, msg)
127
128 # validate itemtype
129 x = _autocast(x, self._field.itemtype)
130 if self._field.itemtype is None:
131 if type(x) not in self._field.supportedTypes and x is not None:
132 msg = f"Value {x} at key {k!r} is of invalid type {_typeStr(x)}"
133 raise FieldValidationError(self._field, self._config, msg)
134 else:
135 if type(x) is not self._field.itemtype and x is not None:
136 msg = (
137 f"Value {x} at key {k!r} is of incorrect type {_typeStr(x)}. "
138 f"Expected type {_typeStr(self._field.itemtype)}"
139 )
140 raise FieldValidationError(self._field, self._config, msg)
141
142 # validate key using keycheck
143 if self._field.keyCheck is not None and not self._field.keyCheck(k):
144 msg = f"Key {k!r} is not a valid key"
145 raise FieldValidationError(self._field, self._config, msg)
146
147 # validate item using itemcheck
148 if self._field.itemCheck is not None and not self._field.itemCheck(x):
149 msg = f"Item at key {k!r} is not a valid value: {x}"
150 raise FieldValidationError(self._field, self._config, msg)
151
152 if at is None:
153 at = getCallStack()
154
155 self._dict[k] = x
156 if setHistory:
157 self._history.append((dict(self._dict), at, label))
158

◆ __str__()

lsst.pex.config.dictField.Dict.__str__ ( self)
inherited

Definition at line 174 of file dictField.py.

174 def __str__(self):
175 return str(self._dict)
176

◆ _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.dictField.DictField._compare ( self,
instance1,
instance2,
shortcut,
rtol,
atol,
output )
protected
Compare two fields for equality.

Used by `lsst.pex.ConfigDictField.compare`.

Parameters
----------
instance1 : `lsst.pex.config.Config`
    Left-hand side config instance to compare.
instance2 : `lsst.pex.config.Config`
    Right-hand side config instance to compare.
shortcut : `bool`
    If `True`, this function returns as soon as an inequality if found.
rtol : `float`
    Relative tolerance for floating point comparisons.
atol : `float`
    Absolute tolerance for floating point comparisons.
output : callable
    A callable that takes a string, used (possibly repeatedly) to
    report inequalities.

Returns
-------
isEqual : 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.

Reimplemented in lsst.pex.config.configDictField.ConfigDictField.

Definition at line 406 of file dictField.py.

406 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
407 """Compare two fields for equality.
408
409 Used by `lsst.pex.ConfigDictField.compare`.
410
411 Parameters
412 ----------
413 instance1 : `lsst.pex.config.Config`
414 Left-hand side config instance to compare.
415 instance2 : `lsst.pex.config.Config`
416 Right-hand side config instance to compare.
417 shortcut : `bool`
418 If `True`, this function returns as soon as an inequality if found.
419 rtol : `float`
420 Relative tolerance for floating point comparisons.
421 atol : `float`
422 Absolute tolerance for floating point comparisons.
423 output : callable
424 A callable that takes a string, used (possibly repeatedly) to
425 report inequalities.
426
427 Returns
428 -------
429 isEqual : bool
430 `True` if the fields are equal, `False` otherwise.
431
432 Notes
433 -----
434 Floating point comparisons are performed by `numpy.allclose`.
435 """
436 d1 = getattr(instance1, self.name)
437 d2 = getattr(instance2, self.name)
438 name = getComparisonName(
439 _joinNamePath(instance1._name, self.name), _joinNamePath(instance2._name, self.name)
440 )
441 if d1 is None or d2 is None:
442 return compareScalars(name, d1, d2, output=output)
443 if not compareScalars(f"{name} (keys)", set(d1.keys()), set(d2.keys()), output=output):
444 return False
445 equal = True
446 for k, v1 in d1.items():
447 v2 = d2[k]
448 result = compareScalars(
449 f"{name}[{k!r}]", v1, v2, dtype=self.itemtype, rtol=rtol, atol=atol, output=output
450 )
451 if not result and shortcut:
452 return False
453 equal = equal and result
454 return equal

◆ _config()

Config lsst.pex.config.dictField.Dict._config ( self)
protectedinherited

Definition at line 92 of file dictField.py.

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

◆ _parseTypingArgs()

Mapping[str, Any] lsst.pex.config.dictField.DictField._parseTypingArgs ( tuple[type, ...] | tuple[str, ...] params,
Mapping[str, Any] kwds )
staticprotected
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 from lsst.pex.config.config.Field.

Definition at line 263 of file dictField.py.

265 ) -> Mapping[str, Any]:
266 if len(params) != 2:
267 raise ValueError("Only tuples of types that are length 2 are supported")
268 resultParams = []
269 for typ in params:
270 if isinstance(typ, str):
271 _typ = ForwardRef(typ)
272 # type ignore below because typeshed seems to be wrong. It
273 # indicates there are only 2 args, as it was in python 3.8, but
274 # 3.9+ takes 3 args.
275 result = _typ._evaluate(globals(), locals(), recursive_guard=set()) # type: ignore
276 if result is None:
277 raise ValueError("Could not deduce type from input")
278 typ = cast(type, result)
279 resultParams.append(typ)
280 keyType, itemType = resultParams
281 results = dict(kwds)
282 if (supplied := kwds.get("keytype")) and supplied != keyType:
283 raise ValueError("Conflicting definition for keytype")
284 else:
285 results["keytype"] = keyType
286 if (supplied := kwds.get("itemtype")) and supplied != itemType:
287 raise ValueError("Conflicting definition for itemtype")
288 else:
289 results["itemtype"] = itemType
290 return results
291

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

◆ 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.dictField.DictField.toDict ( self,
instance )
Convert this field's key-value pairs into a regular `dict`.

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

Returns
-------
result : `dict` or `None`
    If this field has a value of `None`, then this method returns
    `None`. Otherwise, this method returns the field's value as a
    regular Python `dict`.

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

Reimplemented in lsst.pex.config.configDictField.ConfigDictField.

Definition at line 388 of file dictField.py.

388 def toDict(self, instance):
389 """Convert this field's key-value pairs into a regular `dict`.
390
391 Parameters
392 ----------
393 instance : `lsst.pex.config.Config`
394 The configuration that contains this field.
395
396 Returns
397 -------
398 result : `dict` or `None`
399 If this field has a value of `None`, then this method returns
400 `None`. Otherwise, this method returns the field's value as a
401 regular Python `dict`.
402 """
403 value = self.__get__(instance)
404 return dict(value) if value is not None else None
405

◆ validate()

lsst.pex.config.dictField.DictField.validate ( self,
instance )
Validate the field's value (for internal use only).

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

Raises
------
lsst.pex.config.FieldValidationError
    Raised if validation fails for this field (see *Notes*).

Notes
-----
This method validates values according to the following criteria:

- A non-optional field is not `None`.
- If a value is not `None`, it must pass the `ConfigField.dictCheck`
  user callback function.

Individual key and item checks by the ``keyCheck`` and ``itemCheck``
user callback functions are done immediately when the value is set on a
key. Those checks are not repeated by this method.

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

Reimplemented in lsst.pex.config.configDictField.ConfigDictField.

Definition at line 336 of file dictField.py.

336 def validate(self, instance):
337 """Validate the field's value (for internal use only).
338
339 Parameters
340 ----------
341 instance : `lsst.pex.config.Config`
342 The configuration that contains this field.
343
344 Raises
345 ------
346 lsst.pex.config.FieldValidationError
347 Raised if validation fails for this field (see *Notes*).
348
349 Notes
350 -----
351 This method validates values according to the following criteria:
352
353 - A non-optional field is not `None`.
354 - If a value is not `None`, it must pass the `ConfigField.dictCheck`
355 user callback function.
356
357 Individual key and item checks by the ``keyCheck`` and ``itemCheck``
358 user callback functions are done immediately when the value is set on a
359 key. Those checks are not repeated by this method.
360 """
361 Field.validate(self, instance)
362 value = self.__get__(instance)
363 if value is not None and self.dictCheck is not None and not self.dictCheck(value):
364 msg = f"{value} is not a valid value"
365 raise FieldValidationError(self, instance, msg)
366

Member Data Documentation

◆ _config

lsst.pex.config.dictField.Dict._config
protectedinherited

Definition at line 87 of file dictField.py.

◆ _config_

lsst.pex.config.dictField.Dict._config_ = weakref.ref(config)
protectedinherited

Definition at line 76 of file dictField.py.

◆ _dict

lsst.pex.config.dictField.Dict._dict = {}
protectedinherited

Definition at line 77 of file dictField.py.

◆ _field

lsst.pex.config.dictField.Dict._field = field
protectedinherited

Definition at line 75 of file dictField.py.

◆ _history

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

Definition at line 78 of file dictField.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.

◆ dictCheck

lsst.pex.config.dictField.DictField.dictCheck = dictCheck

Definition at line 332 of file dictField.py.

◆ DictClass

type lsst.pex.config.dictField.DictField.DictClass = Dict
static

Definition at line 260 of file dictField.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.dictField.DictField.itemCheck = itemCheck

Definition at line 334 of file dictField.py.

◆ itemtype

lsst.pex.config.dictField.DictField.itemtype = itemtype

Definition at line 331 of file dictField.py.

◆ keyCheck

lsst.pex.config.dictField.DictField.keyCheck = keyCheck

Definition at line 333 of file dictField.py.

◆ keytype

lsst.pex.config.dictField.DictField.keytype = keytype

Definition at line 330 of file dictField.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.dictField.Dict.history = property(lambda x: x._history)
staticinherited

Definition at line 99 of file dictField.py.


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