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.configDictField.ConfigDictField Class Reference
Inheritance diagram for lsst.pex.config.configDictField.ConfigDictField:
lsst.pex.config.dictField.DictField lsst.pex.config.config.Field lsst.pex.config.dictField.Dict

Public Member Functions

 __init__ (self, doc, keytype, itemtype, default=None, optional=False, dictCheck=None, keyCheck=None, itemCheck=None, deprecated=None)
 
 rename (self, instance)
 
 validate (self, instance)
 
 toDict (self, instance)
 
 save (self, outfile, instance)
 
 freeze (self, instance)
 
None __set__ (self, Config instance, Mapping[KeyTypeVar, ItemTypeVar]|None value, Any at=None, str label="assignment")
 
 __class_getitem__ (cls, tuple[type,...]|type|ForwardRef params)
 
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

 _collectImports (self, instance, imports)
 
 _compare (self, instance1, instance2, shortcut, rtol, atol, output)
 
Dict[KeyTypeVar, ItemTypeVar]|None _copy_storage (self, Config old, Config new)
 
 _setup (self, doc, dtype, default, check, optional, source, deprecated)
 
 _validateValue (self, value)
 
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 is a
mapping of keys to `~lsst.pex.config.Config` instances.

``ConfigDictField`` behaves like `DictField` except that the
``itemtype`` must be a `~lsst.pex.config.Config` subclass.

Parameters
----------
doc : `str`
    A description of the configuration field.
keytype : {`int`, `float`, `complex`, `bool`, `str`}
    The type of the mapping keys. All keys must have this type.
itemtype : `lsst.pex.config.Config`-type
    The type of the values in the mapping. This must be
    `~lsst.pex.config.Config` or a subclass.
default : optional
    Unknown.
default : ``itemtype``-dtype, optional
    Default value of this field.
optional : `bool`, optional
    If `True`, this configuration `~lsst.pex.config.Field` is *optional*.
    Default is `True`.
dictCheck : `~collections.abc.Callable` or `None`, optional
    Callable to check a dict.
keyCheck : `~collections.abc.Callable` or `None`, optional
    Callable to check a key.
itemCheck : `~collections.abc.Callable` or `None`, optional
    Callable to check an item.
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.

Raises
------
ValueError
    Raised if the inputs are invalid:

    - ``keytype`` or ``itemtype`` arguments are not supported types
      (members of `ConfigDictField.supportedTypes`.
    - ``dictCheck``, ``keyCheck`` or ``itemCheck`` is not a callable
      function.

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

Notes
-----
You can use ``ConfigDictField`` to create name-to-config mappings. One use
case is for configuring mappings for dataset types in a Butler. In this
case, the dataset type names are arbitrary and user-selected while the
mapping configurations are known and fixed.

Definition at line 135 of file configDictField.py.

Constructor & Destructor Documentation

◆ __init__()

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

Definition at line 200 of file configDictField.py.

211 ):
212 source = getStackFrame()
213 self._setup(
214 doc=doc,
215 dtype=ConfigDict,
216 default=default,
217 check=None,
218 optional=optional,
219 source=source,
220 deprecated=deprecated,
221 )
222 if keytype not in self.supportedTypes:
223 raise ValueError(f"'keytype' {_typeStr(keytype)} is not a supported type")
224 elif not issubclass(itemtype, Config):
225 raise ValueError(f"'itemtype' {_typeStr(itemtype)} is not a supported type")
226
227 check_errors = []
228 for name, check in (("dictCheck", dictCheck), ("keyCheck", keyCheck), ("itemCheck", itemCheck)):
229 if check is not None and not callable(check):
230 check_errors.append(name)
231 if check_errors:
232 raise ValueError(f"{', '.join(check_errors)} must be callable")
233
234 self.keytype = keytype
235 self.itemtype = itemtype
236 self.dictCheck = dictCheck
237 self.keyCheck = keyCheck
238 self.itemCheck = itemCheck
239

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" )
inherited

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.configDictField.ConfigDictField._collectImports ( self,
instance,
imports )
protected
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 from lsst.pex.config.config.Field.

Definition at line 286 of file configDictField.py.

286 def _collectImports(self, instance, imports):
287 # docstring inherited from Field
288 configDict = self.__get__(instance)
289 if configDict is not None:
290 for v in configDict.values():
291 v._collectImports()
292 imports |= v._imports
293

◆ _compare()

lsst.pex.config.configDictField.ConfigDictField._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.dictField.DictField.

Definition at line 312 of file configDictField.py.

312 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
313 """Compare two fields for equality.
314
315 Used by `lsst.pex.ConfigDictField.compare`.
316
317 Parameters
318 ----------
319 instance1 : `lsst.pex.config.Config`
320 Left-hand side config instance to compare.
321 instance2 : `lsst.pex.config.Config`
322 Right-hand side config instance to compare.
323 shortcut : `bool`
324 If `True`, this function returns as soon as an inequality if found.
325 rtol : `float`
326 Relative tolerance for floating point comparisons.
327 atol : `float`
328 Absolute tolerance for floating point comparisons.
329 output : callable
330 A callable that takes a string, used (possibly repeatedly) to
331 report inequalities.
332
333 Returns
334 -------
335 isEqual : bool
336 `True` if the fields are equal, `False` otherwise.
337
338 Notes
339 -----
340 Floating point comparisons are performed by `numpy.allclose`.
341 """
342 d1 = getattr(instance1, self.name)
343 d2 = getattr(instance2, self.name)
344 name = getComparisonName(
345 _joinNamePath(instance1._name, self.name), _joinNamePath(instance2._name, self.name)
346 )
347 if not compareScalars(f"{name} (keys)", set(d1.keys()), set(d2.keys()), output=output):
348 return False
349 equal = True
350 for k, v1 in d1.items():
351 v2 = d2[k]
352 result = compareConfigs(
353 f"{name}[{k!r}]", v1, v2, shortcut=shortcut, rtol=rtol, atol=atol, output=output
354 )
355 if not result and shortcut:
356 return False
357 equal = equal and result
358 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 )
protectedinherited
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 )
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 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.configDictField.ConfigDictField.freeze ( self,
instance )
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 from lsst.pex.config.config.Field.

Definition at line 306 of file configDictField.py.

306 def freeze(self, instance):
307 configDict = self.__get__(instance)
308 if configDict is not None:
309 for k in configDict:
310 configDict[k].freeze()
311

◆ rename()

lsst.pex.config.configDictField.ConfigDictField.rename ( self,
instance )
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 from lsst.pex.config.config.Field.

Definition at line 240 of file configDictField.py.

240 def rename(self, instance):
241 configDict = self.__get__(instance)
242 if configDict is not None:
243 for k in configDict:
244 fullname = _joinNamePath(instance._name, self.name, k)
245 configDict[k]._rename(fullname)
246

◆ save()

lsst.pex.config.configDictField.ConfigDictField.save ( self,
outfile,
instance )
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 from lsst.pex.config.config.Field.

Definition at line 294 of file configDictField.py.

294 def save(self, outfile, instance):
295 configDict = self.__get__(instance)
296 fullname = _joinNamePath(instance._name, self.name)
297 if configDict is None:
298 outfile.write(f"{fullname}={configDict!r}\n")
299 return
300
301 outfile.write(f"{fullname}={{}}\n")
302 for v in configDict.values():
303 outfile.write(f"{v._name}={_typeStr(v)}()\n")
304 v._save(outfile)
305

◆ toDict()

lsst.pex.config.configDictField.ConfigDictField.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.dictField.DictField.

Definition at line 275 of file configDictField.py.

275 def toDict(self, instance):
276 configDict = self.__get__(instance)
277 if configDict is None:
278 return None
279
280 dict_ = {}
281 for k in configDict:
282 dict_[k] = configDict[k].toDict()
283
284 return dict_
285

◆ validate()

lsst.pex.config.configDictField.ConfigDictField.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 validation fails for this field.

Notes
-----
Individual key checks (``keyCheck``) are applied when each key is added
and are not re-checked by this method.

Reimplemented from lsst.pex.config.dictField.DictField.

Definition at line 247 of file configDictField.py.

247 def validate(self, instance):
248 """Validate the field.
249
250 Parameters
251 ----------
252 instance : `lsst.pex.config.Config`
253 The config instance that contains this field.
254
255 Raises
256 ------
257 lsst.pex.config.FieldValidationError
258 Raised if validation fails for this field.
259
260 Notes
261 -----
262 Individual key checks (``keyCheck``) are applied when each key is added
263 and are not re-checked by this method.
264 """
265 value = self.__get__(instance)
266 if value is not None:
267 for k in value:
268 item = value[k]
269 item.validate()
270 if self.itemCheck is not None and not self.itemCheck(item):
271 msg = f"Item at key {k!r} is not a valid value: {item}"
272 raise FieldValidationError(self, instance, msg)
273 DictField.validate(self, instance)
274

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
inherited

Definition at line 344 of file dictField.py.

◆ DictClass

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

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
inherited

Definition at line 346 of file dictField.py.

◆ itemtype

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

Definition at line 343 of file dictField.py.

◆ keyCheck

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

Definition at line 345 of file dictField.py.

◆ keytype

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

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: