28 __all__ = (
'ConfigurableInstance',
'ConfigurableField')
32 from .config
import Config, Field, _joinNamePath, _typeStr, FieldValidationError
33 from .comparison
import compareConfigs, getComparisonName
34 from .callStack
import getCallStack, getStackFrame
40 """A retargetable configuration in a `ConfigurableField` that proxies
41 a `~lsst.pex.config.Config`.
45 ``ConfigurableInstance`` implements ``__getattr__`` and ``__setattr__``
46 methods that forward to the `~lsst.pex.config.Config` it holds.
47 ``ConfigurableInstance`` adds a `retarget` method.
49 The actual `~lsst.pex.config.Config` instance is accessed using the
50 ``value`` property (e.g. to get its documentation). The associated
51 configurable object (usually a `~lsst.pipe.base.Task`) is accessed
52 using the ``target`` property.
55 def __initValue(self, at, label):
56 """Construct value of field.
60 If field.default is an instance of `lsst.pex.config.ConfigClass`,
61 custom construct ``_value`` with the correct values from default.
62 Otherwise, call ``ConfigClass`` constructor
64 name = _joinNamePath(self.
_config_config._name, self._field.name)
66 storage = self._field.default._storage
69 value = self._ConfigClass(__name=name, __at=at, __label=label, **storage)
70 object.__setattr__(self,
"_value", value)
72 def __init__(self, config, field, at=None, label="default"):
73 object.__setattr__(self,
"_config_", weakref.ref(config))
74 object.__setattr__(self,
"_field", field)
75 object.__setattr__(self,
"__doc__", config)
76 object.__setattr__(self,
"_target", field.target)
77 object.__setattr__(self,
"_ConfigClass", field.ConfigClass)
78 object.__setattr__(self,
"_value",
None)
82 at += [self._field.source]
85 history = config._history.setdefault(field.name, [])
86 history.append((
"Targeted and initialized from defaults", at, label))
89 def _config(self) -> Config:
92 assert(self._config_()
is not None)
93 return self._config_()
95 target = property(
lambda x: x._target)
96 """The targeted configurable (read-only).
99 ConfigClass = property(
lambda x: x._ConfigClass)
100 """The configuration class (read-only)
103 value = property(
lambda x: x._value)
104 """The `ConfigClass` instance (`lsst.pex.config.ConfigClass`-type,
109 """Call the configurable.
113 In addition to the user-provided positional and keyword arguments,
114 the configurable is also provided a keyword argument ``config`` with
115 the value of `ConfigurableInstance.value`.
117 return self.
targettarget(*args, config=self.
valuevalue, **kw)
119 def retarget(self, target, ConfigClass=None, at=None, label="retarget"):
120 """Target a new configurable and ConfigClass
122 if self.
_config_config._frozen:
126 ConfigClass = self._field.validateTarget(target, ConfigClass)
127 except BaseException
as e:
132 object.__setattr__(self,
"_target", target)
134 object.__setattr__(self,
"_ConfigClass", ConfigClass)
137 history = self.
_config_config._history.setdefault(self._field.name, [])
138 msg =
"retarget(target=%s, ConfigClass=%s)" % (_typeStr(target), _typeStr(ConfigClass))
139 history.append((msg, at, label))
142 return getattr(self._value, name)
145 """Pretend to be an instance of ConfigClass.
147 Attributes defined by ConfigurableInstance will shadow those defined
150 if self.
_config_config._frozen:
153 if name
in self.__dict__:
155 object.__setattr__(self, name, value)
159 self._value.
__setattr__(name, value, at=at, label=label)
163 Pretend to be an isntance of ConfigClass.
164 Attributes defiend by ConfigurableInstance will shadow those defined
167 if self.
_config_config._frozen:
172 object.__delattr__(self, name)
173 except AttributeError:
180 """A configuration field (`~lsst.pex.config.Field` subclass) that can be
181 can be retargeted towards a different configurable (often a
182 `lsst.pipe.base.Task` subclass).
184 The ``ConfigurableField`` is often used to configure subtasks, which are
185 tasks (`~lsst.pipe.base.Task`) called by a parent task.
190 A description of the configuration field.
191 target : configurable class
192 The configurable target. Configurables have a ``ConfigClass``
193 attribute. Within the task framework, configurables are
194 `lsst.pipe.base.Task` subclasses)
195 ConfigClass : `lsst.pex.config.Config`-type, optional
196 The subclass of `lsst.pex.config.Config` expected as the configuration
197 class of the ``target``. If ``ConfigClass`` is unset then
198 ``target.ConfigClass`` is used.
199 default : ``ConfigClass``-type, optional
200 The default configuration class. Normally this parameter is not set,
201 and defaults to ``ConfigClass`` (or ``target.ConfigClass``).
202 check : callable, optional
203 Callable that takes the field's value (the ``target``) as its only
204 positional argument, and returns `True` if the ``target`` is valid (and
206 deprecated : None or `str`, optional
207 A description of why this Field is deprecated, including removal date.
208 If not None, the string is appended to the docstring for this Field.
224 You can use the `ConfigurableInstance.apply` method to construct a
225 fully-configured configurable.
229 """Validate the target and configuration class.
234 The configurable being verified.
235 ConfigClass : `lsst.pex.config.Config`-type or `None`
236 The configuration class associated with the ``target``. This can
237 be `None` if ``target`` has a ``ConfigClass`` attribute.
242 Raised if ``ConfigClass`` is `None` and ``target`` does not have a
243 ``ConfigClass`` attribute.
245 Raised if ``ConfigClass`` is not a `~lsst.pex.config.Config`
250 - ``target`` is not callable (callables have a ``__call__``
252 - ``target`` is not startically defined (does not have
253 ``__module__`` or ``__name__`` attributes).
255 if ConfigClass
is None:
257 ConfigClass = target.ConfigClass
259 raise AttributeError(
"'target' must define attribute 'ConfigClass'")
260 if not issubclass(ConfigClass, Config):
261 raise TypeError(
"'ConfigClass' is of incorrect type %s."
262 "'ConfigClass' must be a subclass of Config" % _typeStr(ConfigClass))
263 if not hasattr(target,
'__call__'):
264 raise ValueError(
"'target' must be callable")
265 if not hasattr(target,
'__module__')
or not hasattr(target,
'__name__'):
266 raise ValueError(
"'target' must be statically defined"
267 "(must have '__module__' and '__name__' attributes)")
270 def __init__(self, doc, target, ConfigClass=None, default=None, check=None, deprecated=None):
271 ConfigClass = self.
validateTargetvalidateTarget(target, ConfigClass)
274 default = ConfigClass
275 if default != ConfigClass
and type(default) != ConfigClass:
276 raise TypeError(
"'default' is of incorrect type %s. Expected %s" %
277 (_typeStr(default), _typeStr(ConfigClass)))
280 self.
_setup_setup(doc=doc, dtype=ConfigurableInstance, default=default,
281 check=check, optional=
False, source=source, deprecated=deprecated)
285 def __getOrMake(self, instance, at=None, label="default"):
286 value = instance._storage.get(self.name,
None)
291 instance._storage[self.name] = value
294 def __get__(self, instance, owner=None, at=None, label="default"):
295 if instance
is None or not isinstance(instance, Config):
298 return self.
__getOrMake__getOrMake(instance, at=at, label=label)
300 def __set__(self, instance, value, at=None, label="assignment"):
305 oldValue = self.
__getOrMake__getOrMake(instance, at=at)
307 if isinstance(value, ConfigurableInstance):
308 oldValue.retarget(value.target, value.ConfigClass, at, label)
309 oldValue.update(__at=at, __label=label, **value._storage)
310 elif type(value) == oldValue._ConfigClass:
311 oldValue.update(__at=at, __label=label, **value._storage)
312 elif value == oldValue.ConfigClass:
313 value = oldValue.ConfigClass()
314 oldValue.update(__at=at, __label=label, **value._storage)
316 msg =
"Value %s is of incorrect type %s. Expected %s" % \
317 (value, _typeStr(value), _typeStr(oldValue.ConfigClass))
321 fullname = _joinNamePath(instance._name, self.name)
323 value._rename(fullname)
325 def _collectImports(self, instance, imports):
327 target = value.target
328 imports.add(target.__module__)
329 value.value._collectImports()
330 imports |= value.value._imports
332 def save(self, outfile, instance):
333 fullname = _joinNamePath(instance._name, self.name)
335 target = value.target
337 if target != self.
targettarget:
340 ConfigClass = value.ConfigClass
341 outfile.write(
u"{}.retarget(target={}, ConfigClass={})\n\n".
format(fullname,
343 _typeStr(ConfigClass)))
353 return value.toDict()
359 if self.
checkcheck
is not None and not self.
checkcheck(value):
360 msg =
"%s is not a valid value" % str(value)
364 """Customize deep-copying, because we always want a reference to the
367 WARNING: this must be overridden by subclasses if they change the
368 constructor signature!
371 default=copy.deepcopy(self.
defaultdefault))
373 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
374 """Compare two fields for equality.
376 Used by `lsst.pex.ConfigDictField.compare`.
380 instance1 : `lsst.pex.config.Config`
381 Left-hand side config instance to compare.
382 instance2 : `lsst.pex.config.Config`
383 Right-hand side config instance to compare.
385 If `True`, this function returns as soon as an inequality if found.
387 Relative tolerance for floating point comparisons.
389 Absolute tolerance for floating point comparisons.
391 A callable that takes a string, used (possibly repeatedly) to
392 report inequalities. For example: `print`.
397 `True` if the fields are equal, `False` otherwise.
401 Floating point comparisons are performed by `numpy.allclose`.
403 c1 = getattr(instance1, self.name)._value
404 c2 = getattr(instance2, self.name)._value
406 _joinNamePath(instance1._name, self.name),
407 _joinNamePath(instance2._name, self.name)
409 return compareConfigs(name, c1, c2, shortcut=shortcut, rtol=rtol, atol=atol, output=output)
def __get__(self, instance, owner=None, at=None, label="default")
def _setup(self, doc, dtype, default, check, optional, source, deprecated)
def freeze(self, instance)
def save(self, outfile, instance)
def __init__(self, doc, target, ConfigClass=None, default=None, check=None, deprecated=None)
def validateTarget(self, target, ConfigClass)
def rename(self, instance)
def __set__(self, instance, value, at=None, label="assignment")
def __getOrMake(self, instance, at=None, label="default")
def toDict(self, instance)
def validate(self, instance)
def __get__(self, instance, owner=None, at=None, label="default")
def __deepcopy__(self, memo)
def __getattr__(self, name)
def apply(self, *args, **kw)
def __initValue(self, at, label)
def retarget(self, target, ConfigClass=None, at=None, label="retarget")
def __setattr__(self, name, value, at=None, label="assignment")
def __delattr__(self, name, at=None, label="delete")
def __init__(self, config, field, at=None, label="default")
def getStackFrame(relative=0)
def compareConfigs(name, c1, c2, shortcut=True, rtol=1E-8, atol=1E-8, output=None)
def getComparisonName(name1, name2)
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)