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.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

Dict[KeyTypeVar, ItemTypeVar]|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)
 
Dict _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)
 
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 209 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 304 of file dictField.py.

315 ):
316 source = getStackFrame()
317 self._setup(
318 doc=doc,
319 dtype=Dict,
320 default=default,
321 check=None,
322 optional=optional,
323 source=source,
324 deprecated=deprecated,
325 )
326 if keytype is None:
327 raise ValueError(
328 "keytype must either be supplied as an argument or as a type argument to the class"
329 )
330 if keytype not in self.supportedTypes:
331 raise ValueError(f"'keytype' {_typeStr(keytype)} is not a supported type")
332 elif itemtype is not None and itemtype not in self.supportedTypes:
333 raise ValueError(f"'itemtype' {_typeStr(itemtype)} is not a supported type")
334
335 check_errors = []
336 for name, check in (("dictCheck", dictCheck), ("keyCheck", keyCheck), ("itemCheck", itemCheck)):
337 if check is not None and not callable(check):
338 check_errors.append(name)
339 if check_errors:
340 raise ValueError(f"{', '.join(check_errors)} must be callable")
341
342 self.keytype = keytype
343 self.itemtype = itemtype
344 self.dictCheck = dictCheck
345 self.keyCheck = keyCheck
346 self.itemCheck = itemCheck
347

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 124 of file dictField.py.

124 def __contains__(self, k: Any) -> bool:
125 return k in self._dict
126

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

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

Definition at line 171 of file dictField.py.

173 ) -> None:
174 if self._config._frozen:
175 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")
176
177 del self._dict[k]
178 if setHistory:
179 if at is None:
180 at = getCallStack()
181 self._history.append((dict(self._dict), at, label))
182

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

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

Definition at line 115 of file dictField.py.

115 def __getitem__(self, k: KeyTypeVar) -> ItemTypeVar:
116 return self._dict[k]
117

◆ __iter__()

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

Definition at line 121 of file dictField.py.

121 def __iter__(self) -> Iterator[KeyTypeVar]:
122 return iter(self._dict)
123

◆ __len__()

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

Definition at line 118 of file dictField.py.

118 def __len__(self) -> int:
119 return len(self._dict)
120

◆ __reduce__()

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

Definition at line 201 of file dictField.py.

201 def __reduce__(self):
202 raise UnexpectedProxyUsageError(
203 f"Proxy container for config field {self._field.name} cannot "
204 "be pickled; it should be converted to a built-in container before "
205 "being assigned to other objects or variables."
206 )
207
208

◆ __repr__()

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

Definition at line 183 of file dictField.py.

183 def __repr__(self):
184 return repr(self._dict)
185

◆ __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 379 of file dictField.py.

385 ) -> None:
386 if instance._frozen:
387 msg = f"Cannot modify a frozen Config. Attempting to set field to value {value}"
388 raise FieldValidationError(self, instance, msg)
389
390 if at is None:
391 at = getCallStack()
392 if value is not None:
393 value = self.DictClass(instance, self, value, at=at, label=label)
394 else:
395 history = instance._history.setdefault(self.name, [])
396 history.append((value, at, label))
397
398 instance._storage[self.name] = value
399

◆ __setattr__()

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

Definition at line 189 of file dictField.py.

189 def __setattr__(self, attr, value, at=None, label="assignment"):
190 if hasattr(getattr(self.__class__, attr, None), "__set__"):
191 # This allows properties to work.
192 object.__setattr__(self, attr, value)
193 elif attr in self.__dict__ or attr in ["_field", "_config_", "_history", "_dict", "__doc__"]:
194 # This allows specific private attributes to work.
195 object.__setattr__(self, attr, value)
196 else:
197 # We throw everything else.
198 msg = f"{_typeStr(self._field)} has no attribute {attr}"
199 raise FieldValidationError(self._field, self._config, msg)
200

◆ __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 127 of file dictField.py.

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

◆ __str__()

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

Definition at line 186 of file dictField.py.

186 def __str__(self):
187 return str(self._dict)
188

◆ _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 425 of file dictField.py.

425 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
426 """Compare two fields for equality.
427
428 Used by `lsst.pex.ConfigDictField.compare`.
429
430 Parameters
431 ----------
432 instance1 : `lsst.pex.config.Config`
433 Left-hand side config instance to compare.
434 instance2 : `lsst.pex.config.Config`
435 Right-hand side config instance to compare.
436 shortcut : `bool`
437 If `True`, this function returns as soon as an inequality if found.
438 rtol : `float`
439 Relative tolerance for floating point comparisons.
440 atol : `float`
441 Absolute tolerance for floating point comparisons.
442 output : callable
443 A callable that takes a string, used (possibly repeatedly) to
444 report inequalities.
445
446 Returns
447 -------
448 isEqual : bool
449 `True` if the fields are equal, `False` otherwise.
450
451 Notes
452 -----
453 Floating point comparisons are performed by `numpy.allclose`.
454 """
455 d1 = getattr(instance1, self.name)
456 d2 = getattr(instance2, self.name)
457 name = getComparisonName(
458 _joinNamePath(instance1._name, self.name), _joinNamePath(instance2._name, self.name)
459 )
460 if d1 is None or d2 is None:
461 return compareScalars(name, d1, d2, output=output)
462 if not compareScalars(f"{name} (keys)", set(d1.keys()), set(d2.keys()), output=output):
463 return False
464 equal = True
465 for k, v1 in d1.items():
466 v2 = d2[k]
467 result = compareScalars(
468 f"{name}[{k!r}]", v1, v2, dtype=self.itemtype, rtol=rtol, atol=atol, output=output
469 )
470 if not result and shortcut:
471 return False
472 equal = equal and result
473 return equal

◆ _config()

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

Definition at line 101 of file dictField.py.

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

◆ _copy()

Dict lsst.pex.config.dictField.Dict._copy ( self,
Config config )
protectedinherited

Reimplemented in lsst.pex.config.configDictField.ConfigDict.

Definition at line 112 of file dictField.py.

112 def _copy(self, config: Config) -> Dict:
113 return type(self)(config, self._field, self._dict.copy(), at=None, label="copy", setHistory=False)
114

◆ _copy_storage()

Dict[KeyTypeVar, ItemTypeVar] | None lsst.pex.config.dictField.DictField._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 418 of file dictField.py.

418 def _copy_storage(self, old: Config, new: Config) -> Dict[KeyTypeVar, ItemTypeVar] | None:
419 value: Dict[KeyTypeVar, ItemTypeVar] | None = old._storage[self.name]
420 if value is not None:
421 return value._copy(new)
422 else:
423 return None
424

◆ _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 275 of file dictField.py.

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

◆ _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 400 of file dictField.py.

400 def toDict(self, instance):
401 """Convert this field's key-value pairs into a regular `dict`.
402
403 Parameters
404 ----------
405 instance : `lsst.pex.config.Config`
406 The configuration that contains this field.
407
408 Returns
409 -------
410 result : `dict` or `None`
411 If this field has a value of `None`, then this method returns
412 `None`. Otherwise, this method returns the field's value as a
413 regular Python `dict`.
414 """
415 value = self.__get__(instance)
416 return dict(value) if value is not None else None
417

◆ 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 348 of file dictField.py.

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

Member Data Documentation

◆ _config

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

Definition at line 96 of file dictField.py.

◆ _config_

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

Definition at line 85 of file dictField.py.

◆ _dict

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

Definition at line 86 of file dictField.py.

◆ _field

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

Definition at line 84 of file dictField.py.

◆ _history

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

Definition at line 87 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 344 of file dictField.py.

◆ DictClass

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

Definition at line 272 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 346 of file dictField.py.

◆ itemtype

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

Definition at line 343 of file dictField.py.

◆ keyCheck

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

Definition at line 345 of file dictField.py.

◆ keytype

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

Definition at line 342 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 108 of file dictField.py.


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