LSST Applications 27.0.0,g0265f82a02+469cd937ee,g02d81e74bb+21ad69e7e1,g1470d8bcf6+cbe83ee85a,g2079a07aa2+e67c6346a6,g212a7c68fe+04a9158687,g2305ad1205+94392ce272,g295015adf3+81dd352a9d,g2bbee38e9b+469cd937ee,g337abbeb29+469cd937ee,g3939d97d7f+72a9f7b576,g487adcacf7+71499e7cba,g50ff169b8f+5929b3527e,g52b1c1532d+a6fc98d2e7,g591dd9f2cf+df404f777f,g5a732f18d5+be83d3ecdb,g64a986408d+21ad69e7e1,g858d7b2824+21ad69e7e1,g8a8a8dda67+a6fc98d2e7,g99cad8db69+f62e5b0af5,g9ddcbc5298+d4bad12328,ga1e77700b3+9c366c4306,ga8c6da7877+71e4819109,gb0e22166c9+25ba2f69a1,gb6a65358fc+469cd937ee,gbb8dafda3b+69d3c0e320,gc07e1c2157+a98bf949bb,gc120e1dc64+615ec43309,gc28159a63d+469cd937ee,gcf0d15dbbd+72a9f7b576,gdaeeff99f8+a38ce5ea23,ge6526c86ff+3a7c1ac5f1,ge79ae78c31+469cd937ee,gee10cc3b42+a6fc98d2e7,gf1cff7945b+21ad69e7e1,gfbcc870c63+9a11dc8c8f
LSST Data Management Base Package
Loading...
Searching...
No Matches
configField.py
Go to the documentation of this file.
1# This file is part of pex_config.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
27
28__all__ = ["ConfigField"]
29
30from typing import Any, overload
31
32from .callStack import getCallStack, getStackFrame
33from .comparison import compareConfigs, getComparisonName
34from .config import Config, Field, FieldTypeVar, FieldValidationError, _joinNamePath, _typeStr
35
36
37class ConfigField(Field[FieldTypeVar]):
38 """A configuration field (`~lsst.pex.config.Field` subclass) that takes a
39 `~lsst.pex.config.Config`-type as a value.
40
41 Parameters
42 ----------
43 doc : `str`
44 A description of the configuration field.
45 dtype : `lsst.pex.config.Config`-type
46 The type of the field, which must be a subclass of
47 `lsst.pex.config.Config`.
48 default : `lsst.pex.config.Config`, optional
49 If default is `None`, the field will default to a default-constructed
50 instance of ``dtype``. Additionally, to allow for fewer deep-copies,
51 assigning an instance of ``ConfigField`` to ``dtype`` itself, is
52 considered equivalent to assigning a default-constructed sub-config.
53 This means that the argument default can be ``dtype``, as well as an
54 instance of ``dtype``.
55 check : callable, optional
56 A callback function that validates the field's value, returning `True`
57 if the value is valid, and `False` otherwise.
58 deprecated : None or `str`, optional
59 A description of why this Field is deprecated, including removal date.
60 If not None, the string is appended to the docstring for this Field.
61
62 See Also
63 --------
64 ChoiceField
65 ConfigChoiceField
66 ConfigDictField
67 ConfigurableField
68 DictField
69 Field
70 ListField
71 RangeField
72 RegistryField
73
74 Notes
75 -----
76 The behavior of this type of field is much like that of the base `Field`
77 type.
78
79 Assigning to ``ConfigField`` will update all of the fields in the
80 configuration.
81 """
82
83 def __init__(self, doc, dtype=None, default=None, check=None, deprecated=None):
84 if dtype is None or not issubclass(dtype, Config):
85 raise ValueError("dtype=%s is not a subclass of Config" % _typeStr(dtype))
86 if default is None:
87 default = dtype
88 source = getStackFrame()
89 self._setup(
90 doc=doc,
91 dtype=dtype,
92 default=default,
93 check=check,
94 optional=False,
95 source=source,
96 deprecated=deprecated,
97 )
98
99 @overload
101 self, instance: None, owner: Any = None, at: Any = None, label: str = "default"
102 ) -> "ConfigField[FieldTypeVar]": ...
103
104 @overload
106 self, instance: Config, owner: Any = None, at: Any = None, label: str = "default"
107 ) -> FieldTypeVar: ...
108
109 def __get__(self, instance, owner=None, at=None, label="default"):
110 if instance is None or not isinstance(instance, Config):
111 return self
112 else:
113 value = instance._storage.get(self.namenamename, None)
114 if value is None:
115 at = getCallStack()
116 at.insert(0, self.sourcesource)
117 self.__set____set__(instance, self.defaultdefault, at=at, label="default")
118 return value
119
121 self, instance: Config, value: FieldTypeVar | None, at: Any = None, label: str = "assignment"
122 ) -> None:
123 if instance._frozen:
124 raise FieldValidationError(self, instance, "Cannot modify a frozen Config")
125 name = _joinNamePath(prefix=instance._name, name=self.namenamename)
126
127 if value != self.dtypedtype and type(value) is not self.dtypedtype:
128 msg = "Value {} is of incorrect type {}. Expected {}".format(
129 value,
130 _typeStr(value),
131 _typeStr(self.dtypedtype),
132 )
133 raise FieldValidationError(self, instance, msg)
134
135 if at is None:
136 at = getCallStack()
137
138 oldValue = instance._storage.get(self.namenamename, None)
139 if oldValue is None:
140 if value == self.dtypedtype:
141 instance._storage[self.namenamename] = self.dtypedtype(__name=name, __at=at, __label=label)
142 else:
143 instance._storage[self.namenamename] = self.dtypedtype(
144 __name=name, __at=at, __label=label, **value._storage
145 )
146 else:
147 if value == self.dtypedtype:
148 value = value()
149 oldValue.update(__at=at, __label=label, **value._storage)
150 history = instance._history.setdefault(self.namenamename, [])
151 history.append(("config value set", at, label))
152
153 def rename(self, instance):
154 r"""Rename the field in a `~lsst.pex.config.Config` (for internal use
155 only).
156
157 Parameters
158 ----------
159 instance : `lsst.pex.config.Config`
160 The config instance that contains this field.
161
162 Notes
163 -----
164 This method is invoked by the `lsst.pex.config.Config` object that
165 contains this field and should not be called directly.
166
167 Renaming is only relevant for `~lsst.pex.config.Field` instances that
168 hold subconfigs. `~lsst.pex.config.Field`\s that hold subconfigs should
169 rename each subconfig with the full field name as generated by
170 `lsst.pex.config.config._joinNamePath`.
171 """
172 value = self.__get____get____get____get____get____get__(instance)
173 value._rename(_joinNamePath(instance._name, self.namenamename))
174
175 def _collectImports(self, instance, imports):
176 value = self.__get____get____get____get____get____get__(instance)
177 value._collectImports()
178 imports |= value._imports
179
180 def save(self, outfile, instance):
181 """Save this field to a file (for internal use only).
182
183 Parameters
184 ----------
185 outfile : file-like object
186 A writeable field handle.
187 instance : `~lsst.pex.config.Config`
188 The `~lsst.pex.config.Config` instance that contains this field.
189
190 Notes
191 -----
192 This method is invoked by the `~lsst.pex.config.Config` object that
193 contains this field and should not be called directly.
194
195 The output consists of the documentation string
196 (`lsst.pex.config.Field.doc`) formatted as a Python comment. The second
197 line is formatted as an assignment: ``{fullname}={value}``.
198
199 This output can be executed with Python.
200 """
201 value = self.__get____get____get____get____get____get__(instance)
202 value._save(outfile)
203
204 def freeze(self, instance):
205 """Make this field read-only.
206
207 Parameters
208 ----------
209 instance : `lsst.pex.config.Config`
210 The config instance that contains this field.
211
212 Notes
213 -----
214 Freezing is only relevant for fields that hold subconfigs. Fields which
215 hold subconfigs should freeze each subconfig.
216
217 **Subclasses should implement this method.**
218 """
219 value = self.__get____get____get____get____get____get__(instance)
220 value.freeze()
221
222 def toDict(self, instance):
223 """Convert the field value so that it can be set as the value of an
224 item in a `dict` (for internal use only).
225
226 Parameters
227 ----------
228 instance : `~lsst.pex.config.Config`
229 The `~lsst.pex.config.Config` that contains this field.
230
231 Returns
232 -------
233 value : object
234 The field's value. See *Notes*.
235
236 Notes
237 -----
238 This method invoked by the owning `~lsst.pex.config.Config` object and
239 should not be called directly.
240
241 Simple values are passed through. Complex data structures must be
242 manipulated. For example, a `~lsst.pex.config.Field` holding a
243 subconfig should, instead of the subconfig object, return a `dict`
244 where the keys are the field names in the subconfig, and the values are
245 the field values in the subconfig.
246 """
247 value = self.__get____get____get____get____get____get__(instance)
248 return value.toDict()
249
250 def validate(self, instance):
251 """Validate the field (for internal use only).
252
253 Parameters
254 ----------
255 instance : `lsst.pex.config.Config`
256 The config instance that contains this field.
257
258 Raises
259 ------
260 lsst.pex.config.FieldValidationError
261 Raised if verification fails.
262
263 Notes
264 -----
265 This method provides basic validation:
266
267 - Ensures that the value is not `None` if the field is not optional.
268 - Ensures type correctness.
269 - Ensures that the user-provided ``check`` function is valid.
270
271 Most `~lsst.pex.config.Field` subclasses should call
272 `lsst.pex.config.Field.validate` if they re-implement
273 `~lsst.pex.config.Field.validate`.
274 """
275 value = self.__get____get____get____get____get____get__(instance)
276 value.validate()
277
278 if self.check is not None and not self.check(value):
279 msg = "%s is not a valid value" % str(value)
280 raise FieldValidationError(self, instance, msg)
281
282 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
283 """Compare two fields for equality.
284
285 Used by `ConfigField.compare`.
286
287 Parameters
288 ----------
289 instance1 : `lsst.pex.config.Config`
290 Left-hand side config instance to compare.
291 instance2 : `lsst.pex.config.Config`
292 Right-hand side config instance to compare.
293 shortcut : `bool`
294 If `True`, this function returns as soon as an inequality if found.
295 rtol : `float`
296 Relative tolerance for floating point comparisons.
297 atol : `float`
298 Absolute tolerance for floating point comparisons.
299 output : callable
300 A callable that takes a string, used (possibly repeatedly) to
301 report inequalities.
302
303 Returns
304 -------
305 isEqual : bool
306 `True` if the fields are equal, `False` otherwise.
307
308 Notes
309 -----
310 Floating point comparisons are performed by `numpy.allclose`.
311 """
312 c1 = getattr(instance1, self.namenamename)
313 c2 = getattr(instance2, self.namenamename)
314 name = getComparisonName(
315 _joinNamePath(instance1._name, self.namenamename), _joinNamePath(instance2._name, self.namenamename)
316 )
317 return compareConfigs(name, c1, c2, shortcut=shortcut, rtol=rtol, atol=atol, output=output)
__get__(self, instance, owner=None, at=None, label="default")
Definition config.py:726
FieldTypeVar __get__(self, Config instance, Any owner=None, Any at=None, str label="default")
Definition config.py:724
Field[FieldTypeVar] __get__(self, None instance, Any owner=None, Any at=None, str label="default")
Definition config.py:719
None __set__(self, Config instance, FieldTypeVar|None value, Any at=None, str label="assignment")
Definition config.py:755
_setup(self, doc, dtype, default, check, optional, source, deprecated)
Definition config.py:497
__get__(self, instance, owner=None, at=None, label="default")
None __set__(self, Config instance, FieldTypeVar|None value, Any at=None, str label="assignment")
"ConfigField[FieldTypeVar]" __get__(self, None instance, Any owner=None, Any at=None, str label="default")
_compare(self, instance1, instance2, shortcut, rtol, atol, output)
_collectImports(self, instance, imports)
FieldTypeVar __get__(self, Config instance, Any owner=None, Any at=None, str label="default")
__init__(self, doc, dtype=None, default=None, check=None, deprecated=None)