LSST Applications g0fba68d861+bb7a7cfa1f,g1ec0fe41b4+f536777771,g1fd858c14a+470a99fdf4,g216c3ac8a7+0d4d80193f,g35bb328faa+fcb1d3bbc8,g4d2262a081+23bd310d1b,g53246c7159+fcb1d3bbc8,g56a49b3a55+369644a549,g5a012ec0e7+3632fc3ff3,g60b5630c4e+3bfb9058a5,g67b6fd64d1+ed4b5058f4,g78460c75b0+2f9a1b4bcd,g786e29fd12+cf7ec2a62a,g8180f54f50+60bd39f3b6,g8352419a5c+fcb1d3bbc8,g87d29937c9+57a68d035f,g8852436030+4699110379,g89139ef638+ed4b5058f4,g9125e01d80+fcb1d3bbc8,g94187f82dc+3bfb9058a5,g989de1cb63+ed4b5058f4,g9ccd5d7f00+b7cae620c0,g9d31334357+3bfb9058a5,g9f33ca652e+00883ace41,gabe3b4be73+1e0a283bba,gabf8522325+fa80ff7197,gb1101e3267+27b24065a3,gb58c049af0+f03b321e39,gb89ab40317+ed4b5058f4,gc0af124501+708fe67c54,gcf25f946ba+4699110379,gd6cbbdb0b4+bb83cc51f8,gde0f65d7ad+acd5afb0eb,ge1ad929117+3bfb9058a5,ge278dab8ac+d65b3c2b70,ge410e46f29+ed4b5058f4,gf5e32f922b+fcb1d3bbc8,gf67bdafdda+ed4b5058f4,w.2025.17
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)
 
 _setup (self, doc, dtype, default, check, optional, source, deprecated)
 
 _validateValue (self, value)
 
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 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 110 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 175 of file configDictField.py.

186 ):
187 source = getStackFrame()
188 self._setup(
189 doc=doc,
190 dtype=ConfigDict,
191 default=default,
192 check=None,
193 optional=optional,
194 source=source,
195 deprecated=deprecated,
196 )
197 if keytype not in self.supportedTypes:
198 raise ValueError(f"'keytype' {_typeStr(keytype)} is not a supported type")
199 elif not issubclass(itemtype, Config):
200 raise ValueError(f"'itemtype' {_typeStr(itemtype)} is not a supported type")
201
202 check_errors = []
203 for name, check in (("dictCheck", dictCheck), ("keyCheck", keyCheck), ("itemCheck", itemCheck)):
204 if check is not None and not callable(check):
205 check_errors.append(name)
206 if check_errors:
207 raise ValueError(f"{', '.join(check_errors)} must be callable")
208
209 self.keytype = keytype
210 self.itemtype = itemtype
211 self.dictCheck = dictCheck
212 self.keyCheck = keyCheck
213 self.itemCheck = itemCheck
214

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

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.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 261 of file configDictField.py.

261 def _collectImports(self, instance, imports):
262 # docstring inherited from Field
263 configDict = self.__get__(instance)
264 if configDict is not None:
265 for v in configDict.values():
266 v._collectImports()
267 imports |= v._imports
268

◆ _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 287 of file configDictField.py.

287 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
288 """Compare two fields for equality.
289
290 Used by `lsst.pex.ConfigDictField.compare`.
291
292 Parameters
293 ----------
294 instance1 : `lsst.pex.config.Config`
295 Left-hand side config instance to compare.
296 instance2 : `lsst.pex.config.Config`
297 Right-hand side config instance to compare.
298 shortcut : `bool`
299 If `True`, this function returns as soon as an inequality if found.
300 rtol : `float`
301 Relative tolerance for floating point comparisons.
302 atol : `float`
303 Absolute tolerance for floating point comparisons.
304 output : callable
305 A callable that takes a string, used (possibly repeatedly) to
306 report inequalities.
307
308 Returns
309 -------
310 isEqual : bool
311 `True` if the fields are equal, `False` otherwise.
312
313 Notes
314 -----
315 Floating point comparisons are performed by `numpy.allclose`.
316 """
317 d1 = getattr(instance1, self.name)
318 d2 = getattr(instance2, self.name)
319 name = getComparisonName(
320 _joinNamePath(instance1._name, self.name), _joinNamePath(instance2._name, self.name)
321 )
322 if not compareScalars(f"{name} (keys)", set(d1.keys()), set(d2.keys()), output=output):
323 return False
324 equal = True
325 for k, v1 in d1.items():
326 v2 = d2[k]
327 result = compareConfigs(
328 f"{name}[{k!r}]", v1, v2, shortcut=shortcut, rtol=rtol, atol=atol, output=output
329 )
330 if not result and shortcut:
331 return False
332 equal = equal and result
333 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 )
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 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.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 281 of file configDictField.py.

281 def freeze(self, instance):
282 configDict = self.__get__(instance)
283 if configDict is not None:
284 for k in configDict:
285 configDict[k].freeze()
286

◆ 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 215 of file configDictField.py.

215 def rename(self, instance):
216 configDict = self.__get__(instance)
217 if configDict is not None:
218 for k in configDict:
219 fullname = _joinNamePath(instance._name, self.name, k)
220 configDict[k]._rename(fullname)
221

◆ 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 269 of file configDictField.py.

269 def save(self, outfile, instance):
270 configDict = self.__get__(instance)
271 fullname = _joinNamePath(instance._name, self.name)
272 if configDict is None:
273 outfile.write(f"{fullname}={configDict!r}\n")
274 return
275
276 outfile.write(f"{fullname}={{}}\n")
277 for v in configDict.values():
278 outfile.write(f"{v._name}={_typeStr(v)}()\n")
279 v._save(outfile)
280

◆ 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 250 of file configDictField.py.

250 def toDict(self, instance):
251 configDict = self.__get__(instance)
252 if configDict is None:
253 return None
254
255 dict_ = {}
256 for k in configDict:
257 dict_[k] = configDict[k].toDict()
258
259 return dict_
260

◆ 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 222 of file configDictField.py.

222 def validate(self, instance):
223 """Validate the field.
224
225 Parameters
226 ----------
227 instance : `lsst.pex.config.Config`
228 The config instance that contains this field.
229
230 Raises
231 ------
232 lsst.pex.config.FieldValidationError
233 Raised if validation fails for this field.
234
235 Notes
236 -----
237 Individual key checks (``keyCheck``) are applied when each key is added
238 and are not re-checked by this method.
239 """
240 value = self.__get__(instance)
241 if value is not None:
242 for k in value:
243 item = value[k]
244 item.validate()
245 if self.itemCheck is not None and not self.itemCheck(item):
246 msg = f"Item at key {k!r} is not a valid value: {item}"
247 raise FieldValidationError(self, instance, msg)
248 DictField.validate(self, instance)
249

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
inherited

Definition at line 332 of file dictField.py.

◆ DictClass

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

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
inherited

Definition at line 334 of file dictField.py.

◆ itemtype

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

Definition at line 331 of file dictField.py.

◆ keyCheck

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

Definition at line 333 of file dictField.py.

◆ keytype

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

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: