LSST Applications g00d0e8bbd7+edbf708997,g199a45376c+5137f08352,g1fd858c14a+5d3c95268f,g262e1987ae+129725fbd9,g29ae962dfc+34be89a2fc,g2cef7863aa+73c82f25e4,g3541666cd7+00c381f533,g35bb328faa+edbf708997,g3fd5ace14f+0f9585b40d,g47891489e3+19fcc35de2,g53246c7159+edbf708997,g5b326b94bb+74795fc0b3,g5e032395f3+2a361f5c28,g64539dfbff+33d965bf6c,g67b6fd64d1+19fcc35de2,g74acd417e5+6e038728f1,g786e29fd12+af89c03590,g7aefaa3e3d+a53f4933b3,g87389fa792+a4172ec7da,g88cb488625+cdc2ed4845,g89139ef638+19fcc35de2,g8d7436a09f+1c65fffe91,g8ea07a8fe4+79658f16ab,g90f42f885a+6577634e1f,g9722cb1a7f+d8f85438e7,g98df359435+0f66fdfca5,ga2180abaac+edbf708997,ga9e74d7ce9+128cc68277,gbf99507273+edbf708997,gc2a301910b+33d965bf6c,gca7fc764a6+19fcc35de2,gd7ef33dd92+19fcc35de2,gdab6d2f7ff+6e038728f1,gdbb4c4dda9+33d965bf6c,ge410e46f29+19fcc35de2,ge41e95a9f2+33d965bf6c,ge8e7e3f09d+a09b026073,geaed405ab2+062dfc8cdc,w.2025.45
LSST Data Management Base Package
Loading...
Searching...
No Matches
lsst.pex.config.configurableField.ConfigurableField Class Reference
Inheritance diagram for lsst.pex.config.configurableField.ConfigurableField:
lsst.pex.config.config.Field lsst.pex.config.configurableField.ConfigurableInstance

Public Member Functions

 validateTarget (self, target, ConfigClass)
 
 __init__ (self, doc, target, ConfigClass=None, default=None, check=None, deprecated=None)
 
ConfigurableField __get__ (self, None instance, Any owner=None, Any at=None, str label="default")
 
ConfigurableInstance[FieldTypeVar__get__ (self, Config instance, Any owner=None, Any at=None, str label="default")
 
 __get__ (self, instance, owner=None, at=None, label="default")
 
 __set__ (self, instance, value, at=None, label="assignment")
 
 rename (self, instance)
 
 save (self, outfile, instance)
 
 freeze (self, instance)
 
 toDict (self, instance)
 
 validate (self, instance)
 
 __deepcopy__ (self, memo)
 
 __class_getitem__ (cls, tuple[type,...]|type|ForwardRef params)
 
 __delete__ (self, instance, at=None, label="deletion")
 
 apply (self, *args, **kw)
 
 retarget (self, target, ConfigClass=None, at=None, label="retarget")
 
 __getattr__ (self, name)
 
 __setattr__ (self, name, value, at=None, label="assignment")
 
 __delattr__ (self, name, at=None, label="delete")
 
 __reduce__ (self)
 

Public Attributes

 dtype = dtype
 
 doc = doc
 
 deprecated = deprecated
 
 default = default
 
 check = check
 
 optional = optional
 
 source = source
 

Static Public Attributes

dict supportedTypes = {str, bool, float, int, complex}
 

Protected Member Functions

 _collectImports (self, instance, imports)
 
ConfigurableInstance|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)
 
Config _config (self)
 
ConfigurableInstance _copy (self, Config parent)
 

Static Protected Member Functions

Mapping[str, Any] _parseTypingArgs (tuple[type,...]|tuple[str,...] params, Mapping[str, Any] kwds)
 

Protected Attributes

 _field = self._field.validateTarget(target, ConfigClass)
 
 _target
 
 _ConfigClass
 
 _config
 
 _value
 

Properties

 target = property(lambda x: x._target)
 
 ConfigClass = property(lambda x: x._ConfigClass)
 
 value = property(lambda x: x._value)
 

Detailed Description

A configuration field (`~lsst.pex.config.Field` subclass) that can be
can be retargeted towards a different configurable (often a
`lsst.pipe.base.Task` subclass).

The ``ConfigurableField`` is often used to configure subtasks, which are
tasks (`~lsst.pipe.base.Task`) called by a parent task.

Parameters
----------
doc : `str`
    A description of the configuration field.
target : configurable class
    The configurable target. Configurables have a ``ConfigClass``
    attribute. Within the task framework, configurables are
    `lsst.pipe.base.Task` subclasses).
ConfigClass : `lsst.pex.config.Config`-type, optional
    The subclass of `lsst.pex.config.Config` expected as the configuration
    class of the ``target``. If ``ConfigClass`` is unset then
    ``target.ConfigClass`` is used.
default : ``ConfigClass``-type, optional
    The default configuration class. Normally this parameter is not set,
    and defaults to ``ConfigClass`` (or ``target.ConfigClass``).
check : callable, optional
    Callable that takes the field's value (the ``target``) as its only
    positional argument, and returns `True` if the ``target`` is valid (and
    `False` otherwise).
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
DictField
Field
ListField
RangeField
RegistryField

Notes
-----
You can use the `ConfigurableInstance.apply` method to construct a
fully-configured configurable.

Definition at line 238 of file configurableField.py.

Constructor & Destructor Documentation

◆ __init__()

lsst.pex.config.configurableField.ConfigurableField.__init__ ( self,
doc,
target,
ConfigClass = None,
default = None,
check = None,
deprecated = None )

Definition at line 332 of file configurableField.py.

332 def __init__(self, doc, target, ConfigClass=None, default=None, check=None, deprecated=None):
333 ConfigClass = self.validateTarget(target, ConfigClass)
334
335 if default is None:
336 default = ConfigClass
337 if default != ConfigClass and type(default) is not ConfigClass:
338 raise TypeError(
339 f"'default' is of incorrect type {_typeStr(default)}. Expected {_typeStr(ConfigClass)}"
340 )
341
342 source = getStackFrame()
343 self._setup(
344 doc=doc,
345 dtype=ConfigurableInstance,
346 default=default,
347 check=check,
348 optional=False,
349 source=source,
350 deprecated=deprecated,
351 )
352 self.target = target
353 self.ConfigClass = ConfigClass
354

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

◆ __deepcopy__()

lsst.pex.config.configurableField.ConfigurableField.__deepcopy__ ( self,
memo )
Customize deep-copying, because we always want a reference to the
original typemap.

WARNING: this must be overridden by subclasses if they change the
constructor signature!

Definition at line 458 of file configurableField.py.

458 def __deepcopy__(self, memo):
459 """Customize deep-copying, because we always want a reference to the
460 original typemap.
461
462 WARNING: this must be overridden by subclasses if they change the
463 constructor signature!
464 """
465 return type(self)(
466 doc=self.doc,
467 target=self.target,
468 ConfigClass=self.ConfigClass,
469 default=copy.deepcopy(self.default),
470 )
471

◆ __delattr__()

lsst.pex.config.configurableField.ConfigurableInstance.__delattr__ ( self,
name,
at = None,
label = "delete" )
inherited
Pretend to be an isntance of  ConfigClass.
Attributes defiend by ConfigurableInstance will shadow those defined
in ConfigClass.

Definition at line 212 of file configurableField.py.

212 def __delattr__(self, name, at=None, label="delete"):
213 """
214 Pretend to be an isntance of ConfigClass.
215 Attributes defiend by ConfigurableInstance will shadow those defined
216 in ConfigClass.
217 """
218 if self._config._frozen:
219 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")
220
221 try:
222 # attribute exists in the ConfigurableInstance wrapper
223 object.__delattr__(self, name)
224 except AttributeError:
225 if at is None:
226 at = getCallStack()
227 self._value.__delattr__(name, at=at, label=label)
228

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

◆ __get__() [1/3]

ConfigurableInstance[FieldTypeVar] lsst.pex.config.configurableField.ConfigurableField.__get__ ( self,
Config instance,
Any owner = None,
Any at = None,
str label = "default" )

Definition at line 376 of file configurableField.py.

378 ) -> ConfigurableInstance[FieldTypeVar]: ...
379

◆ __get__() [2/3]

lsst.pex.config.configurableField.ConfigurableField.__get__ ( self,
instance,
owner = None,
at = None,
label = "default" )

Definition at line 380 of file configurableField.py.

380 def __get__(self, instance, owner=None, at=None, label="default"):
381 if instance is None or not isinstance(instance, Config):
382 return self
383 else:
384 return self.__getOrMake(instance, at=at, label=label)
385

◆ __get__() [3/3]

ConfigurableField lsst.pex.config.configurableField.ConfigurableField.__get__ ( self,
None instance,
Any owner = None,
Any at = None,
str label = "default" )

Definition at line 371 of file configurableField.py.

373 ) -> ConfigurableField: ...
374

◆ __getattr__()

lsst.pex.config.configurableField.ConfigurableInstance.__getattr__ ( self,
name )
inherited

Definition at line 192 of file configurableField.py.

192 def __getattr__(self, name):
193 return getattr(self._value, name)
194

◆ __reduce__()

lsst.pex.config.configurableField.ConfigurableInstance.__reduce__ ( self)
inherited

Definition at line 229 of file configurableField.py.

229 def __reduce__(self):
230 raise UnexpectedProxyUsageError(
231 f"Proxy object for config field {self._field.name} cannot "
232 "be pickled; it should be converted to a normal `Config` instance "
233 "via the `value` property before being assigned to other objects "
234 "or variables."
235 )
236
237

◆ __set__()

lsst.pex.config.configurableField.ConfigurableField.__set__ ( self,
instance,
value,
at = None,
label = "assignment" )

Definition at line 386 of file configurableField.py.

386 def __set__(self, instance, value, at=None, label="assignment"):
387 if instance._frozen:
388 raise FieldValidationError(self, instance, "Cannot modify a frozen Config")
389 if at is None:
390 at = getCallStack()
391 oldValue = self.__getOrMake(instance, at=at)
392
393 if isinstance(value, ConfigurableInstance):
394 oldValue.retarget(value.target, value.ConfigClass, at, label)
395 oldValue.update(__at=at, __label=label, **value._storage)
396 elif type(value) is oldValue._ConfigClass:
397 oldValue.update(__at=at, __label=label, **value._storage)
398 elif value == oldValue.ConfigClass:
399 value = oldValue.ConfigClass()
400 oldValue.update(__at=at, __label=label, **value._storage)
401 else:
402 msg = (
403 f"Value {value} is of incorrect type {_typeStr(value)}. "
404 f"Expected {_typeStr(oldValue.ConfigClass)}"
405 )
406 raise FieldValidationError(self, instance, msg)
407

◆ __setattr__()

lsst.pex.config.configurableField.ConfigurableInstance.__setattr__ ( self,
name,
value,
at = None,
label = "assignment" )
inherited
Pretend to be an instance of ConfigClass.

Attributes defined by ConfigurableInstance will shadow those defined
in ConfigClass

Definition at line 195 of file configurableField.py.

195 def __setattr__(self, name, value, at=None, label="assignment"):
196 """Pretend to be an instance of ConfigClass.
197
198 Attributes defined by ConfigurableInstance will shadow those defined
199 in ConfigClass
200 """
201 if self._config._frozen:
202 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")
203
204 if name in self.__dict__:
205 # attribute exists in the ConfigurableInstance wrapper
206 object.__setattr__(self, name, value)
207 else:
208 if at is None:
209 at = getCallStack()
210 self._value.__setattr__(name, value, at=at, label=label)
211

◆ _collectImports()

lsst.pex.config.configurableField.ConfigurableField._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 413 of file configurableField.py.

413 def _collectImports(self, instance, imports):
414 value = self.__get__(instance)
415 target = value.target
416 imports.add(target.__module__)
417 value.value._collectImports()
418 imports |= value.value._imports
419

◆ _compare()

lsst.pex.config.configurableField.ConfigurableField._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. For example: `print`.

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.

Definition at line 472 of file configurableField.py.

472 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
473 """Compare two fields for equality.
474
475 Used by `lsst.pex.ConfigDictField.compare`.
476
477 Parameters
478 ----------
479 instance1 : `lsst.pex.config.Config`
480 Left-hand side config instance to compare.
481 instance2 : `lsst.pex.config.Config`
482 Right-hand side config instance to compare.
483 shortcut : `bool`
484 If `True`, this function returns as soon as an inequality if found.
485 rtol : `float`
486 Relative tolerance for floating point comparisons.
487 atol : `float`
488 Absolute tolerance for floating point comparisons.
489 output : callable
490 A callable that takes a string, used (possibly repeatedly) to
491 report inequalities. For example: `print`.
492
493 Returns
494 -------
495 isEqual : bool
496 `True` if the fields are equal, `False` otherwise.
497
498 Notes
499 -----
500 Floating point comparisons are performed by `numpy.allclose`.
501 """
502 c1 = getattr(instance1, self.name)._value
503 c2 = getattr(instance2, self.name)._value
504 name = getComparisonName(
505 _joinNamePath(instance1._name, self.name), _joinNamePath(instance2._name, self.name)
506 )
507 return compareConfigs(name, c1, c2, shortcut=shortcut, rtol=rtol, atol=atol, output=output)

◆ _config()

Config lsst.pex.config.configurableField.ConfigurableInstance._config ( self)
protectedinherited

Definition at line 121 of file configurableField.py.

121 def _config(self) -> Config:
122 # Config Fields should never outlive their config class instance
123 # assert that as such here
124 assert self._config_() is not None
125 return self._config_()
126

◆ _copy()

ConfigurableInstance lsst.pex.config.configurableField.ConfigurableInstance._copy ( self,
Config parent )
protectedinherited

Definition at line 110 of file configurableField.py.

110 def _copy(self, parent: Config) -> ConfigurableInstance:
111 result = object.__new__(ConfigurableInstance)
112 object.__setattr__(result, "_config_", weakref.ref(parent))
113 object.__setattr__(result, "_field", self._field)
114 object.__setattr__(result, "__doc__", self.__doc__)
115 object.__setattr__(result, "_target", self._target)
116 object.__setattr__(result, "_ConfigClass", self._ConfigClass)
117 object.__setattr__(result, "_value", self._value.copy())
118 return result
119

◆ _copy_storage()

ConfigurableInstance | None lsst.pex.config.configurableField.ConfigurableField._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 443 of file configurableField.py.

443 def _copy_storage(self, old: Config, new: Config) -> ConfigurableInstance | None:
444 instance: ConfigurableInstance | None = old._storage.get(self.name)
445 if instance is not None:
446 return instance._copy(new)
447 else:
448 return None
449

◆ _parseTypingArgs()

Mapping[str, Any] lsst.pex.config.configurableField.ConfigurableField._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 356 of file configurableField.py.

358 ) -> Mapping[str, Any]:
359 return kwds
360

◆ _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

◆ apply()

lsst.pex.config.configurableField.ConfigurableInstance.apply ( self,
* args,
** kw )
inherited
Call the configurable.

Parameters
----------
*args : `~typing.Any`
    Arguments to use when calling the configurable.
**kw : `~typing.Any`
    Keyword parameters to use when calling.

Notes
-----
In addition to the user-provided positional and keyword arguments,
the configurable is also provided a keyword argument ``config`` with
the value of `ConfigurableInstance.value`.

Definition at line 140 of file configurableField.py.

140 def apply(self, *args, **kw):
141 """Call the configurable.
142
143 Parameters
144 ----------
145 *args : `~typing.Any`
146 Arguments to use when calling the configurable.
147 **kw : `~typing.Any`
148 Keyword parameters to use when calling.
149
150 Notes
151 -----
152 In addition to the user-provided positional and keyword arguments,
153 the configurable is also provided a keyword argument ``config`` with
154 the value of `ConfigurableInstance.value`.
155 """
156 return self.target(*args, config=self.value, **kw)
157

◆ freeze()

lsst.pex.config.configurableField.ConfigurableField.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 435 of file configurableField.py.

435 def freeze(self, instance):
436 value = self.__getOrMake(instance)
437 value.freeze()
438

◆ rename()

lsst.pex.config.configurableField.ConfigurableField.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 408 of file configurableField.py.

408 def rename(self, instance):
409 fullname = _joinNamePath(instance._name, self.name)
410 value = self.__getOrMake(instance)
411 value._rename(fullname)
412

◆ retarget()

lsst.pex.config.configurableField.ConfigurableInstance.retarget ( self,
target,
ConfigClass = None,
at = None,
label = "retarget" )
inherited
Target a new configurable and ConfigClass.

Parameters
----------
target : `type`
    Item to retarget.
ConfigClass : `type` or `None`, optional
    New config class to use.
at : `list` of `~lsst.pex.config.callStack.StackFrame` or `None`,\
        optional
    Stack for history recording.
label : `str`, optional
    Label for history recording.

Definition at line 158 of file configurableField.py.

158 def retarget(self, target, ConfigClass=None, at=None, label="retarget"):
159 """Target a new configurable and ConfigClass.
160
161 Parameters
162 ----------
163 target : `type`
164 Item to retarget.
165 ConfigClass : `type` or `None`, optional
166 New config class to use.
167 at : `list` of `~lsst.pex.config.callStack.StackFrame` or `None`,\
168 optional
169 Stack for history recording.
170 label : `str`, optional
171 Label for history recording.
172 """
173 if self._config._frozen:
174 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")
175
176 try:
177 ConfigClass = self._field.validateTarget(target, ConfigClass)
178 except BaseException as e:
179 raise FieldValidationError(self._field, self._config, e.message) from e
180
181 if at is None:
182 at = getCallStack()
183 object.__setattr__(self, "_target", target)
184 if ConfigClass != self.ConfigClass:
185 object.__setattr__(self, "_ConfigClass", ConfigClass)
186 self.__initValue(at, label)
187
188 history = self._config._history.setdefault(self._field.name, [])
189 msg = f"retarget(target={_typeStr(target)}, ConfigClass={_typeStr(ConfigClass)})"
190 history.append((msg, at, label))
191

◆ save()

lsst.pex.config.configurableField.ConfigurableField.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 420 of file configurableField.py.

420 def save(self, outfile, instance):
421 fullname = _joinNamePath(instance._name, self.name)
422 value = self.__getOrMake(instance)
423 target = value.target
424
425 if target != self.target:
426 # not targeting the field-default target.
427 # save target information
428 ConfigClass = value.ConfigClass
429 outfile.write(
430 f"{fullname}.retarget(target={_typeStr(target)}, ConfigClass={_typeStr(ConfigClass)})\n\n"
431 )
432 # save field values
433 value._save(outfile)
434

◆ toDict()

lsst.pex.config.configurableField.ConfigurableField.toDict ( self,
instance )
Convert the field value so that it can be set as the value of an
item in a `dict` (for internal use only).

Parameters
----------
instance : `~lsst.pex.config.Config`
    The `~lsst.pex.config.Config` that contains this field.

Returns
-------
value : object
    The field's value. See *Notes*.

Notes
-----
This method invoked by the owning `~lsst.pex.config.Config` object and
should not be called directly.

Simple values are passed through. Complex data structures must be
manipulated. For example, a `~lsst.pex.config.Field` holding a
subconfig should, instead of the subconfig object, return a `dict`
where the keys are the field names in the subconfig, and the values are
the field values in the subconfig.

Reimplemented from lsst.pex.config.config.Field.

Definition at line 439 of file configurableField.py.

439 def toDict(self, instance):
440 value = self.__get__(instance)
441 return value.toDict()
442

◆ validate()

lsst.pex.config.configurableField.ConfigurableField.validate ( self,
instance )
Validate the field (for internal use only).

Parameters
----------
instance : `lsst.pex.config.Config`
    The config instance that contains this field.

Raises
------
lsst.pex.config.FieldValidationError
    Raised if verification fails.

Notes
-----
This method provides basic validation:

- Ensures that the value is not `None` if the field is not optional.
- Ensures type correctness.
- Ensures that the user-provided ``check`` function is valid.

Most `~lsst.pex.config.Field` subclasses should call
`lsst.pex.config.Field.validate` if they re-implement
`~lsst.pex.config.Field.validate`.

Reimplemented from lsst.pex.config.config.Field.

Definition at line 450 of file configurableField.py.

450 def validate(self, instance):
451 value = self.__get__(instance)
452 value.validate()
453
454 if self.check is not None and not self.check(value):
455 msg = f"{value} is not a valid value"
456 raise FieldValidationError(self, instance, msg)
457

◆ validateTarget()

lsst.pex.config.configurableField.ConfigurableField.validateTarget ( self,
target,
ConfigClass )
Validate the target and configuration class.

Parameters
----------
target : configurable class
    The configurable being verified.
ConfigClass : `lsst.pex.config.Config`-type or `None`
    The configuration class associated with the ``target``. This can
    be `None` if ``target`` has a ``ConfigClass`` attribute.

Raises
------
AttributeError
    Raised if ``ConfigClass`` is `None` and ``target`` does not have a
    ``ConfigClass`` attribute.
TypeError
    Raised if ``ConfigClass`` is not a `~lsst.pex.config.Config`
    subclass.
ValueError
    Raised if:

    - ``target`` is not callable (callables have a ``__call__``
      method).
    - ``target`` is not startically defined (does not have
      ``__module__`` or ``__name__`` attributes).

Definition at line 287 of file configurableField.py.

287 def validateTarget(self, target, ConfigClass):
288 """Validate the target and configuration class.
289
290 Parameters
291 ----------
292 target : configurable class
293 The configurable being verified.
294 ConfigClass : `lsst.pex.config.Config`-type or `None`
295 The configuration class associated with the ``target``. This can
296 be `None` if ``target`` has a ``ConfigClass`` attribute.
297
298 Raises
299 ------
300 AttributeError
301 Raised if ``ConfigClass`` is `None` and ``target`` does not have a
302 ``ConfigClass`` attribute.
303 TypeError
304 Raised if ``ConfigClass`` is not a `~lsst.pex.config.Config`
305 subclass.
306 ValueError
307 Raised if:
308
309 - ``target`` is not callable (callables have a ``__call__``
310 method).
311 - ``target`` is not startically defined (does not have
312 ``__module__`` or ``__name__`` attributes).
313 """
314 if ConfigClass is None:
315 try:
316 ConfigClass = target.ConfigClass
317 except Exception as e:
318 raise AttributeError("'target' must define attribute 'ConfigClass'") from e
319 if not issubclass(ConfigClass, Config):
320 raise TypeError(
321 f"'ConfigClass' is of incorrect type {_typeStr(ConfigClass)}. "
322 "'ConfigClass' must be a subclass of Config"
323 )
324 if not callable(target):
325 raise ValueError("'target' must be callable")
326 if not hasattr(target, "__module__") or not hasattr(target, "__name__"):
327 raise ValueError(
328 "'target' must be statically defined (must have '__module__' and '__name__' attributes)"
329 )
330 return ConfigClass
331

Member Data Documentation

◆ _config

lsst.pex.config.configurableField.ConfigurableInstance._config
protectedinherited

Definition at line 174 of file configurableField.py.

◆ _ConfigClass

lsst.pex.config.configurableField.ConfigurableInstance._ConfigClass
protectedinherited

Definition at line 116 of file configurableField.py.

◆ _field

lsst.pex.config.configurableField.ConfigurableInstance._field = self._field.validateTarget(target, ConfigClass)
protectedinherited

Definition at line 113 of file configurableField.py.

◆ _target

lsst.pex.config.configurableField.ConfigurableInstance._target
protectedinherited

Definition at line 115 of file configurableField.py.

◆ _value

lsst.pex.config.configurableField.ConfigurableInstance._value
protectedinherited

Definition at line 193 of file configurableField.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.

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

◆ 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

◆ ConfigClass

lsst.pex.config.configurableField.ConfigurableInstance.ConfigClass = property(lambda x: x._ConfigClass)
staticinherited

Definition at line 131 of file configurableField.py.

◆ target

lsst.pex.config.configurableField.ConfigurableInstance.target = property(lambda x: x._target)
staticinherited

Definition at line 127 of file configurableField.py.

◆ value

lsst.pex.config.configurableField.ConfigurableInstance.value = property(lambda x: x._value)
staticinherited

Definition at line 135 of file configurableField.py.


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