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.configChoiceField.ConfigChoiceField Class Reference
Inheritance diagram for lsst.pex.config.configChoiceField.ConfigChoiceField:
lsst.pex.config.config.Field lsst.pex.config.configChoiceField.ConfigInstanceDict lsst.pex.config.config.Config lsst.pex.config.config.ConfigMeta lsst.pex.config.registry.RegistryField

Public Member Functions

 __init__ (self, doc, typemap, default=None, optional=False, multi=False, deprecated=None)
 
 __class_getitem__ (cls, tuple[type,...]|type|ForwardRef params)
 
ConfigChoiceField __get__ (self, None instance, Any owner=None, Any at=None, str label="default")
 
ConfigInstanceDict __get__ (self, Config instance, Any owner=None, Any at=None, str label="default")
 
 __get__ (self, instance, owner=None, at=None, label="default")
 
None __set__ (self, Config instance, ConfigInstanceDict|None value, Any at=None, str label="assignment")
 
 rename (self, instance)
 
 validate (self, instance)
 
 toDict (self, instance)
 
 freeze (self, instance)
 
 save (self, outfile, instance)
 
 __deepcopy__ (self, memo)
 
 __delete__ (self, instance, at=None, label="deletion")
 
 types (self)
 
 __contains__ (self, k)
 
 __len__ (self)
 
 __iter__ (self)
 
 __getitem__ (self, k, at=None, label="default")
 
 __setitem__ (self, k, value, at=None, label="assignment")
 
 __setattr__ (self, attr, value, at=None, label="assignment")
 
 __reduce__ (self)
 
 keys (self)
 
 values (self)
 
 items (self)
 
 __new__ (cls, *args, **kw)
 
Config copy (self)
 
 setDefaults (self)
 
 update (self, **kw)
 
 load (self, filename, root="config")
 
 loadFromStream (self, stream, root="config", filename=None, extraLocals=None)
 
 loadFromString (self, code, root="config", filename=None, extraLocals=None)
 
 saveToString (self, skipImports=False)
 
 saveToStream (self, outfile, root="config", skipImports=False)
 
 formatHistory (self, name, **kwargs)
 
 __delattr__ (self, attr, at=None, label="deletion")
 
 __eq__ (self, other)
 
 __ne__ (self, other)
 
 __str__ (self)
 
 __repr__ (self)
 
 compare (self, other, shortcut=True, rtol=1e-8, atol=1e-8, output=None)
 
 __init_subclass__ (cls, **kwargs)
 

Public Attributes

 typemap = typemap
 
 multi = multi
 
 dtype = dtype
 
 doc = doc
 
 deprecated = deprecated
 
 default = default
 
 check = check
 
 optional = optional
 
 source = source
 
 types
 

Static Public Attributes

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

Protected Member Functions

 _getOrMake (self, instance, label="default")
 
Any _copy_storage (self, Config old, Config new)
 
 _collectImports (self, instance, imports)
 
 _compare (self, instance1, instance2, shortcut, rtol, atol, output)
 
 _setup (self, doc, dtype, default, check, optional, source, deprecated)
 
 _validateValue (self, value)
 
ConfigInstanceDict _copy (self, Config config)
 
 _setSelection (self, value, at=None, label="assignment")
 
 _getNames (self)
 
 _setNames (self, value)
 
 _delNames (self)
 
 _getName (self)
 
 _setName (self, value)
 
 _delName (self)
 
 _getActive (self)
 
 _rename (self, fullname)
 
 _save (self, outfile)
 
 _fromPython (cls, config_py)
 

Static Protected Member Functions

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

Protected Attributes

dict _dict = {}
 
 _selection = None
 
 _config = config
 
 _field = field
 
 _typemap = None
 
bool _frozen = True
 
 _name = name
 
dict _fields = {}
 
 _source = getStackFrame()
 

Static Protected Attributes

dict _storage [str, Any]
 
dict _history [str, list[Any]]
 
set _imports [Any]
 

Properties

 names = property(_getNames, _setNames, _delNames)
 
 name = property(_getName, _setName, _delName)
 
 active = property(_getActive)
 
 history = property(lambda x: x._history)
 

Detailed Description

A configuration field (`~lsst.pex.config.Field` subclass) that allows a
user to choose from a set of `~lsst.pex.config.Config` types.

Parameters
----------
doc : `str`
    Documentation string for the field.
typemap : `dict`-like
    A mapping between keys and `~lsst.pex.config.Config`-types as values.
    See *Examples* for details.
default : `str`, optional
    The default configuration name.
optional : `bool`, optional
    When `False`, `lsst.pex.config.Config.validate` will fail if the
    field's value is `None`.
multi : `bool`, optional
    If `True`, the field allows multiple selections. In this case, set the
    selections by assigning a sequence to the ``names`` attribute of the
    field.

    If `False`, the field allows only a single selection. In this case,
    set the active config by assigning the config's key from the
    ``typemap`` to the field's ``name`` attribute (see *Examples*).
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
ConfigDictField
ConfigField
ConfigurableField
DictField
Field
ListField
RangeField
RegistryField

Notes
-----
``ConfigChoiceField`` instances can allow either single selections or
multiple selections, depending on the ``multi`` parameter. For
single-selection fields, set the selection with the ``name`` attribute.
For multi-selection fields, set the selection though the ``names``
attribute.

This field is validated only against the active selection. If the
``active`` attribute is `None` and the field is not optional, validation
will fail.

When saving a configuration with a ``ConfigChoiceField``, the entire set is
saved, as well as the active selection.

Examples
--------
While the ``typemap`` is shared by all instances of the field, each
instance of the field has its own instance of a particular sub-config type.

For example, ``AaaConfig`` is a config object

>>> from lsst.pex.config import Config, ConfigChoiceField, Field
>>> class AaaConfig(Config):
...     somefield = Field("doc", int)

The ``MyConfig`` config has a ``ConfigChoiceField`` field called ``choice``
that maps the ``AaaConfig`` type to the ``"AAA"`` key:

>>> TYPEMAP = {"AAA", AaaConfig}
>>> class MyConfig(Config):
...     choice = ConfigChoiceField("doc for choice", TYPEMAP)

Creating an instance of ``MyConfig``:

>>> instance = MyConfig()

Setting value of the field ``somefield`` on the "AAA" key of the ``choice``
field:

>>> instance.choice["AAA"].somefield = 5

**Selecting the active configuration**

Make the ``"AAA"`` key the active configuration value for the ``choice``
field:

>>> instance.choice = "AAA"

Alternatively, the last line can be written:

>>> instance.choice.name = "AAA"

(If the config instance allows multiple selections, you'd assign a sequence
to the ``names`` attribute instead.)

``ConfigChoiceField`` instances also allow multiple values of the same
type:

>>> TYPEMAP["CCC"] = AaaConfig
>>> TYPEMAP["BBB"] = AaaConfig

Definition at line 391 of file configChoiceField.py.

Constructor & Destructor Documentation

◆ __init__()

lsst.pex.config.configChoiceField.ConfigChoiceField.__init__ ( self,
doc,
typemap,
default = None,
optional = False,
multi = False,
deprecated = None )

Definition at line 496 of file configChoiceField.py.

496 def __init__(self, doc, typemap, default=None, optional=False, multi=False, deprecated=None):
497 source = getStackFrame()
498 self._setup(
499 doc=doc,
500 dtype=self.instanceDictClass,
501 default=default,
502 check=None,
503 optional=optional,
504 source=source,
505 deprecated=deprecated,
506 )
507 self.typemap = typemap
508 self.multi = multi
509

Member Function Documentation

◆ __class_getitem__()

lsst.pex.config.configChoiceField.ConfigChoiceField.__class_getitem__ ( cls,
tuple[type, ...] | type | ForwardRef params )

Definition at line 510 of file configChoiceField.py.

510 def __class_getitem__(cls, params: tuple[type, ...] | type | ForwardRef):
511 raise ValueError("ConfigChoiceField does not support typing argument")
512

◆ __contains__()

lsst.pex.config.configChoiceField.ConfigInstanceDict.__contains__ ( self,
k )
inherited

Definition at line 204 of file configChoiceField.py.

204 def __contains__(self, k):
205 return k in self.types
206

◆ __deepcopy__()

lsst.pex.config.configChoiceField.ConfigChoiceField.__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 619 of file configChoiceField.py.

619 def __deepcopy__(self, memo):
620 """Customize deep-copying, because we always want a reference to the
621 original typemap.
622
623 WARNING: this must be overridden by subclasses if they change the
624 constructor signature!
625 """
626 other = type(self)(
627 doc=self.doc,
628 typemap=self.typemap,
629 default=copy.deepcopy(self.default),
630 optional=self.optional,
631 multi=self.multi,
632 )
633 other.source = self.source
634 return other
635

◆ __delattr__()

lsst.pex.config.config.Config.__delattr__ ( self,
attr,
at = None,
label = "deletion" )
inherited

Definition at line 1617 of file config.py.

1617 def __delattr__(self, attr, at=None, label="deletion"):
1618 if attr in self._fields:
1619 if at is None:
1620 at = getCallStack()
1621 self._fields[attr].__delete__(self, at=at, label=label)
1622 else:
1623 object.__delattr__(self, attr)
1624

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

◆ __eq__()

lsst.pex.config.config.Config.__eq__ ( self,
other )
inherited

Definition at line 1625 of file config.py.

1625 def __eq__(self, other):
1626 if type(other) is type(self):
1627 for name in self._fields:
1628 thisValue = getattr(self, name)
1629 otherValue = getattr(other, name)
1630 if isinstance(thisValue, float) and math.isnan(thisValue):
1631 if not math.isnan(otherValue):
1632 return False
1633 elif thisValue != otherValue:
1634 return False
1635 return True
1636 return False
1637

◆ __get__() [1/3]

ConfigInstanceDict lsst.pex.config.configChoiceField.ConfigChoiceField.__get__ ( self,
Config instance,
Any owner = None,
Any at = None,
str label = "default" )

Definition at line 531 of file configChoiceField.py.

533 ) -> ConfigInstanceDict: ...
534

◆ __get__() [2/3]

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

Definition at line 535 of file configChoiceField.py.

535 def __get__(self, instance, owner=None, at=None, label="default"):
536 if instance is None or not isinstance(instance, Config):
537 return self
538 else:
539 return self._getOrMake(instance)
540

◆ __get__() [3/3]

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

Definition at line 526 of file configChoiceField.py.

528 ) -> ConfigChoiceField: ...
529

◆ __getitem__()

lsst.pex.config.configChoiceField.ConfigInstanceDict.__getitem__ ( self,
k,
at = None,
label = "default" )
inherited

Definition at line 300 of file configChoiceField.py.

300 def __getitem__(self, k, at=None, label="default"):
301 try:
302 value = self._dict[k]
303 except KeyError:
304 try:
305 dtype = self.types[k]
306 except Exception as e:
307 raise FieldValidationError(
308 self._field, self._config, f"Unknown key {k!r} in Registry/ConfigChoiceField"
309 ) from e
310 name = _joinNamePath(self._config._name, self._field.name, k)
311 if at is None:
312 at = getCallStack()
313 at.insert(0, dtype._source)
314 value = self._dict.setdefault(k, dtype(__name=name, __at=at, __label=label))
315 return value
316

◆ __init_subclass__()

lsst.pex.config.config.Config.__init_subclass__ ( cls,
** kwargs )
inherited
Run initialization for every subclass.

Specifically registers the subclass with a YAML representer
and YAML constructor (if pyyaml is available)

Definition at line 1694 of file config.py.

1694 def __init_subclass__(cls, **kwargs):
1695 """Run initialization for every subclass.
1696
1697 Specifically registers the subclass with a YAML representer
1698 and YAML constructor (if pyyaml is available)
1699 """
1700 super().__init_subclass__(**kwargs)
1701
1702 if not yaml:
1703 return
1704
1705 yaml.add_representer(cls, _yaml_config_representer)
1706

◆ __iter__()

lsst.pex.config.configChoiceField.ConfigInstanceDict.__iter__ ( self)
inherited

Definition at line 210 of file configChoiceField.py.

210 def __iter__(self):
211 return iter(self.types)
212

◆ __len__()

lsst.pex.config.configChoiceField.ConfigInstanceDict.__len__ ( self)
inherited

Definition at line 207 of file configChoiceField.py.

207 def __len__(self):
208 return len(self.types)
209

◆ __ne__()

lsst.pex.config.config.Config.__ne__ ( self,
other )
inherited

Definition at line 1638 of file config.py.

1638 def __ne__(self, other):
1639 return not self.__eq__(other)
1640

◆ __new__()

lsst.pex.config.config.Config.__new__ ( cls,
* args,
** kw )
inherited
Allocate a new `lsst.pex.config.Config` object.

In order to ensure that all Config object are always in a proper state
when handed to users or to derived `~lsst.pex.config.Config` classes,
some attributes are handled at allocation time rather than at
initialization.

This ensures that even if a derived `~lsst.pex.config.Config` class
implements ``__init__``, its author does not need to be concerned about
when or even the base ``Config.__init__`` should be called.

Definition at line 1033 of file config.py.

1033 def __new__(cls, *args, **kw):
1034 """Allocate a new `lsst.pex.config.Config` object.
1035
1036 In order to ensure that all Config object are always in a proper state
1037 when handed to users or to derived `~lsst.pex.config.Config` classes,
1038 some attributes are handled at allocation time rather than at
1039 initialization.
1040
1041 This ensures that even if a derived `~lsst.pex.config.Config` class
1042 implements ``__init__``, its author does not need to be concerned about
1043 when or even the base ``Config.__init__`` should be called.
1044 """
1045 name = kw.pop("__name", None)
1046 at = kw.pop("__at", getCallStack())
1047 # remove __label and ignore it
1048 kw.pop("__label", "default")
1049
1050 instance = object.__new__(cls)
1051 instance._frozen = False
1052 instance._name = name
1053 instance._storage = {}
1054 instance._history = {}
1055 instance._imports = set()
1056 # load up defaults
1057 for field in instance._fields.values():
1058 instance._history[field.name] = []
1059 field.__set__(instance, field.default, at=at + [field.source], label="default")
1060 # set custom default-overrides
1061 instance.setDefaults()
1062 # set constructor overrides
1063 instance.update(__at=at, **kw)
1064 return instance
1065

◆ __reduce__()

lsst.pex.config.configChoiceField.ConfigInstanceDict.__reduce__ ( self)
inherited

Definition at line 383 of file configChoiceField.py.

383 def __reduce__(self):
384 raise UnexpectedProxyUsageError(
385 f"Proxy container for config field {self._field.name} cannot "
386 "be pickled; it should be converted to a built-in container before "
387 "being assigned to other objects or variables."
388 )
389
390

◆ __repr__()

lsst.pex.config.config.Config.__repr__ ( self)
inherited

Definition at line 1644 of file config.py.

1644 def __repr__(self):
1645 return "{}({})".format(
1646 _typeStr(self),
1647 ", ".join(f"{k}={v!r}" for k, v in self.toDict().items() if v is not None),
1648 )
1649

◆ __set__()

None lsst.pex.config.configChoiceField.ConfigChoiceField.__set__ ( self,
Config instance,
ConfigInstanceDict | None value,
Any at = None,
str label = "assignment" )

Definition at line 541 of file configChoiceField.py.

543 ) -> None:
544 if instance._frozen:
545 raise FieldValidationError(self, instance, "Cannot modify a frozen Config")
546 if at is None:
547 at = getCallStack()
548 instanceDict = self._getOrMake(instance)
549 if isinstance(value, self.instanceDictClass):
550 for k, v in value.items():
551 instanceDict.__setitem__(k, v, at=at, label=label)
552 instanceDict._setSelection(value._selection, at=at, label=label)
553
554 else:
555 instanceDict._setSelection(value, at=at, label=label)
556

◆ __setattr__()

lsst.pex.config.configChoiceField.ConfigInstanceDict.__setattr__ ( self,
attr,
value,
at = None,
label = "assignment" )
inherited

Definition at line 351 of file configChoiceField.py.

351 def __setattr__(self, attr, value, at=None, label="assignment"):
352 if hasattr(getattr(self.__class__, attr, None), "__set__"):
353 # This allows properties to work.
354 object.__setattr__(self, attr, value)
355 elif attr in self.__dict__ or attr in [
356 "_history",
357 "_field",
358 "_config",
359 "_dict",
360 "_selection",
361 "__doc__",
362 "_typemap",
363 ]:
364 # This allows specific private attributes to work.
365 object.__setattr__(self, attr, value)
366 else:
367 # We throw everything else.
368 msg = f"{_typeStr(self._field)} has no attribute {attr}"
369 raise FieldValidationError(self._field, self._config, msg)
370

◆ __setitem__()

lsst.pex.config.configChoiceField.ConfigInstanceDict.__setitem__ ( self,
k,
value,
at = None,
label = "assignment" )
inherited

Definition at line 317 of file configChoiceField.py.

317 def __setitem__(self, k, value, at=None, label="assignment"):
318 if self._config._frozen:
319 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")
320
321 try:
322 dtype = self.types[k]
323 except Exception as e:
324 raise FieldValidationError(self._field, self._config, f"Unknown key {k!r}") from e
325
326 if value != dtype and type(value) is not dtype:
327 msg = (
328 f"Value {value} at key {k} is of incorrect type {_typeStr(value)}. "
329 f"Expected type {_typeStr(dtype)}"
330 )
331 raise FieldValidationError(self._field, self._config, msg)
332
333 if at is None:
334 at = getCallStack()
335 name = _joinNamePath(self._config._name, self._field.name, k)
336 oldValue = self._dict.get(k, None)
337 if oldValue is None:
338 if value == dtype:
339 self._dict[k] = value(__name=name, __at=at, __label=label)
340 else:
341 self._dict[k] = dtype(__name=name, __at=at, __label=label, **value._storage)
342 else:
343 if value == dtype:
344 value = value()
345 oldValue.update(__at=at, __label=label, **value._storage)
346

◆ __str__()

lsst.pex.config.config.Config.__str__ ( self)
inherited

Definition at line 1641 of file config.py.

1641 def __str__(self):
1642 return str(self.toDict())
1643

◆ _collectImports()

lsst.pex.config.configChoiceField.ConfigChoiceField._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 603 of file configChoiceField.py.

603 def _collectImports(self, instance, imports):
604 instanceDict = self.__get__(instance)
605 for config in instanceDict.values():
606 config._collectImports()
607 imports |= config._imports
608

◆ _compare()

lsst.pex.config.configChoiceField.ConfigChoiceField._compare ( self,
instance1,
instance2,
shortcut,
rtol,
atol,
output )
protected
Compare two fields for equality.

Used by `lsst.pex.ConfigChoiceField.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
-----
Only the selected configurations are compared, as the parameters of any
others do not matter.

Floating point comparisons are performed by `numpy.allclose`.

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

Definition at line 636 of file configChoiceField.py.

636 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
637 """Compare two fields for equality.
638
639 Used by `lsst.pex.ConfigChoiceField.compare`.
640
641 Parameters
642 ----------
643 instance1 : `lsst.pex.config.Config`
644 Left-hand side config instance to compare.
645 instance2 : `lsst.pex.config.Config`
646 Right-hand side config instance to compare.
647 shortcut : `bool`
648 If `True`, this function returns as soon as an inequality if found.
649 rtol : `float`
650 Relative tolerance for floating point comparisons.
651 atol : `float`
652 Absolute tolerance for floating point comparisons.
653 output : callable
654 A callable that takes a string, used (possibly repeatedly) to
655 report inequalities.
656
657 Returns
658 -------
659 isEqual : bool
660 `True` if the fields are equal, `False` otherwise.
661
662 Notes
663 -----
664 Only the selected configurations are compared, as the parameters of any
665 others do not matter.
666
667 Floating point comparisons are performed by `numpy.allclose`.
668 """
669 d1 = getattr(instance1, self.name)
670 d2 = getattr(instance2, self.name)
671 name = getComparisonName(
672 _joinNamePath(instance1._name, self.name), _joinNamePath(instance2._name, self.name)
673 )
674 if not compareScalars(f"selection for {name}", d1._selection, d2._selection, output=output):
675 return False
676 if d1._selection is None:
677 return True
678 if self.multi:
679 nested = [(k, d1[k], d2[k]) for k in d1._selection]
680 else:
681 nested = [(d1._selection, d1[d1._selection], d2[d1._selection])]
682 equal = True
683 for k, c1, c2 in nested:
684 result = compareConfigs(
685 f"{name}[{k!r}]", c1, c2, shortcut=shortcut, rtol=rtol, atol=atol, output=output
686 )
687 if not result and shortcut:
688 return False
689 equal = equal and result
690 return equal

◆ _copy()

ConfigInstanceDict lsst.pex.config.configChoiceField.ConfigInstanceDict._copy ( self,
Config config )
protectedinherited

Definition at line 188 of file configChoiceField.py.

188 def _copy(self, config: Config) -> ConfigInstanceDict:
189 result = type(self)(config, self._field)
190 result._dict = {k: v.copy() for k, v in self._dict.items()}
191 result._history.extend(self._history)
192 result._typemap = self._typemap
193 if self._selection is not None:
194 if self._field.multi:
195 result._selection = SelectionSet(result._dict, self._selection._set)
196 else:
197 result._selection = self._selection
198 return result
199

◆ _copy_storage()

Any lsst.pex.config.configChoiceField.ConfigChoiceField._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 557 of file configChoiceField.py.

557 def _copy_storage(self, old: Config, new: Config) -> Any:
558 instance_dict: ConfigInstanceDict | None = old._storage.get(self.name)
559 if instance_dict is not None:
560 return instance_dict._copy(new)
561 else:
562 return None
563

◆ _delName()

lsst.pex.config.configChoiceField.ConfigInstanceDict._delName ( self)
protectedinherited

Definition at line 265 of file configChoiceField.py.

265 def _delName(self):
266 if self._field.multi:
267 raise FieldValidationError(
268 self._field, self._config, "Multi-selection field has no attribute 'name'"
269 )
270 self._selection = None
271

◆ _delNames()

lsst.pex.config.configChoiceField.ConfigInstanceDict._delNames ( self)
protectedinherited

Definition at line 244 of file configChoiceField.py.

244 def _delNames(self):
245 if not self._field.multi:
246 raise FieldValidationError(
247 self._field, self._config, "Single-selection field has no attribute 'names'"
248 )
249 self._selection = None
250

◆ _fromPython()

lsst.pex.config.config.Config._fromPython ( cls,
config_py )
protectedinherited
Instantiate a `Config`-subclass from serialized Python form.

Parameters
----------
config_py : `str`
    A serialized form of the Config as created by
    `Config.saveToStream`.

Returns
-------
config : `Config`
    Reconstructed `Config` instant.

Definition at line 1708 of file config.py.

1708 def _fromPython(cls, config_py):
1709 """Instantiate a `Config`-subclass from serialized Python form.
1710
1711 Parameters
1712 ----------
1713 config_py : `str`
1714 A serialized form of the Config as created by
1715 `Config.saveToStream`.
1716
1717 Returns
1718 -------
1719 config : `Config`
1720 Reconstructed `Config` instant.
1721 """
1722 cls = _classFromPython(config_py)
1723 return unreduceConfig(cls, config_py)
1724
1725

◆ _getActive()

lsst.pex.config.configChoiceField.ConfigInstanceDict._getActive ( self)
protectedinherited

Definition at line 284 of file configChoiceField.py.

284 def _getActive(self):
285 if self._selection is None:
286 return None
287
288 if self._field.multi:
289 return [self[c] for c in self._selection]
290 else:
291 return self[self._selection]
292

◆ _getName()

lsst.pex.config.configChoiceField.ConfigInstanceDict._getName ( self)
protectedinherited

Definition at line 251 of file configChoiceField.py.

251 def _getName(self):
252 if self._field.multi:
253 raise FieldValidationError(
254 self._field, self._config, "Multi-selection field has no attribute 'name'"
255 )
256 return self._selection
257

◆ _getNames()

lsst.pex.config.configChoiceField.ConfigInstanceDict._getNames ( self)
protectedinherited

Definition at line 230 of file configChoiceField.py.

230 def _getNames(self):
231 if not self._field.multi:
232 raise FieldValidationError(
233 self._field, self._config, "Single-selection field has no attribute 'names'"
234 )
235 return self._selection
236

◆ _getOrMake()

lsst.pex.config.configChoiceField.ConfigChoiceField._getOrMake ( self,
instance,
label = "default" )
protected

Definition at line 513 of file configChoiceField.py.

513 def _getOrMake(self, instance, label="default"):
514 instanceDict = instance._storage.get(self.name)
515 if instanceDict is None:
516 at = getCallStack(1)
517 instanceDict = self.dtype(instance, self)
518 instanceDict.__doc__ = self.doc
519 instance._storage[self.name] = instanceDict
520 history = instance._history.setdefault(self.name, [])
521 history.append(("Initialized from defaults", at, label))
522
523 return instanceDict
524

◆ _parseTypingArgs()

Mapping[str, Any] lsst.pex.config.config.Field._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 in lsst.pex.config.configurableField.ConfigurableField, and lsst.pex.config.dictField.DictField.

Definition at line 410 of file config.py.

412 ) -> Mapping[str, Any]:
413 """Parse type annotations into keyword constructor arguments.
414
415 This is a special private method that interprets type arguments (i.e.
416 Field[str]) into keyword arguments to be passed on to the constructor.
417
418 Subclasses of Field can implement this method to customize how they
419 handle turning type parameters into keyword arguments (see DictField
420 for an example)
421
422 Parameters
423 ----------
424 params : `tuple` of `type` or `tuple` of str
425 Parameters passed to the type annotation. These will either be
426 types or strings. Strings are to interpreted as forward references
427 and will be treated as such.
428 kwds : `MutableMapping` with keys of `str` and values of `Any`
429 These are the user supplied keywords that are to be passed to the
430 Field constructor.
431
432 Returns
433 -------
434 kwds : `MutableMapping` with keys of `str` and values of `Any`
435 The mapping of keywords that will be passed onto the constructor
436 of the Field. Should be filled in with any information gleaned
437 from the input parameters.
438
439 Raises
440 ------
441 ValueError
442 Raised if params is of incorrect length.
443 Raised if a forward reference could not be resolved
444 Raised if there is a conflict between params and values in kwds
445 """
446 if len(params) > 1:
447 raise ValueError("Only single type parameters are supported")
448 unpackedParams = params[0]
449 if isinstance(unpackedParams, str):
450 _typ = ForwardRef(unpackedParams)
451 # type ignore below because typeshed seems to be wrong. It
452 # indicates there are only 2 args, as it was in python 3.8, but
453 # 3.9+ takes 3 args.
454 result = _typ._evaluate(globals(), locals(), recursive_guard=set()) # type: ignore
455 if result is None:
456 raise ValueError("Could not deduce type from input")
457 unpackedParams = cast(type, result)
458 if "dtype" in kwds and kwds["dtype"] != unpackedParams:
459 raise ValueError("Conflicting definition for dtype")
460 elif "dtype" not in kwds:
461 kwds = {**kwds, **{"dtype": unpackedParams}}
462 return kwds
463

◆ _rename()

lsst.pex.config.configChoiceField.ConfigInstanceDict._rename ( self,
name )
protectedinherited
Rename this config object in its parent `~lsst.pex.config.Config`.

Parameters
----------
name : `str`
    New name for this config in its parent `~lsst.pex.config.Config`.

Notes
-----
This method uses the `~lsst.pex.config.Field.rename` method of
individual `lsst.pex.config.Field` instances.
`lsst.pex.config.Field` subclasses may need to implement a ``rename``
method for *this* method to work.

See Also
--------
lsst.pex.config.Field.rename

Reimplemented from lsst.pex.config.config.Config.

Definition at line 347 of file configChoiceField.py.

347 def _rename(self, fullname):
348 for k, v in self._dict.items():
349 v._rename(_joinNamePath(name=fullname, index=k))
350

◆ _save()

lsst.pex.config.config.Config._save ( self,
outfile )
protectedinherited
Save this config to an open stream object.

Parameters
----------
outfile : file-like object
    Destination file object write the config into. Accepts strings not
    bytes.

Definition at line 1426 of file config.py.

1426 def _save(self, outfile):
1427 """Save this config to an open stream object.
1428
1429 Parameters
1430 ----------
1431 outfile : file-like object
1432 Destination file object write the config into. Accepts strings not
1433 bytes.
1434 """
1435 for field in self._fields.values():
1436 field.save(outfile, self)
1437

◆ _setName()

lsst.pex.config.configChoiceField.ConfigInstanceDict._setName ( self,
value )
protectedinherited

Definition at line 258 of file configChoiceField.py.

258 def _setName(self, value):
259 if self._field.multi:
260 raise FieldValidationError(
261 self._field, self._config, "Multi-selection field has no attribute 'name'"
262 )
263 self._setSelection(value)
264

◆ _setNames()

lsst.pex.config.configChoiceField.ConfigInstanceDict._setNames ( self,
value )
protectedinherited

Definition at line 237 of file configChoiceField.py.

237 def _setNames(self, value):
238 if not self._field.multi:
239 raise FieldValidationError(
240 self._field, self._config, "Single-selection field has no attribute 'names'"
241 )
242 self._setSelection(value)
243

◆ _setSelection()

lsst.pex.config.configChoiceField.ConfigInstanceDict._setSelection ( self,
value,
at = None,
label = "assignment" )
protectedinherited

Definition at line 213 of file configChoiceField.py.

213 def _setSelection(self, value, at=None, label="assignment"):
214 if self._config._frozen:
215 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")
216
217 if at is None:
218 at = getCallStack(1)
219
220 if value is None:
221 self._selection = None
222 elif self._field.multi:
223 self._selection = SelectionSet(self, value, setHistory=False)
224 else:
225 if value not in self._dict:
226 self.__getitem__(value, at=at) # just invoke __getitem__ to make sure it's present
227 self._selection = value
228 self._history.append((value, at, label))
229

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

◆ compare()

lsst.pex.config.config.Config.compare ( self,
other,
shortcut = True,
rtol = 1e-8,
atol = 1e-8,
output = None )
inherited
Compare this configuration to another `~lsst.pex.config.Config` for
equality.

Parameters
----------
other : `lsst.pex.config.Config`
    Other `~lsst.pex.config.Config` object to compare against this
    config.
shortcut : `bool`, optional
    If `True`, return as soon as an inequality is found. Default is
    `True`.
rtol : `float`, optional
    Relative tolerance for floating point comparisons.
atol : `float`, optional
    Absolute tolerance for floating point comparisons.
output : callable, optional
    A callable that takes a string, used (possibly repeatedly) to
    report inequalities.

Returns
-------
isEqual : `bool`
    `True` when the two `lsst.pex.config.Config` instances are equal.
    `False` if there is an inequality.

See Also
--------
lsst.pex.config.compareConfigs

Notes
-----
Unselected targets of `~lsst.pex.config.RegistryField` fields and
unselected choices of `~lsst.pex.config.ConfigChoiceField` fields
are not considered by this method.

Floating point comparisons are performed by `numpy.allclose`.

Definition at line 1650 of file config.py.

1650 def compare(self, other, shortcut=True, rtol=1e-8, atol=1e-8, output=None):
1651 """Compare this configuration to another `~lsst.pex.config.Config` for
1652 equality.
1653
1654 Parameters
1655 ----------
1656 other : `lsst.pex.config.Config`
1657 Other `~lsst.pex.config.Config` object to compare against this
1658 config.
1659 shortcut : `bool`, optional
1660 If `True`, return as soon as an inequality is found. Default is
1661 `True`.
1662 rtol : `float`, optional
1663 Relative tolerance for floating point comparisons.
1664 atol : `float`, optional
1665 Absolute tolerance for floating point comparisons.
1666 output : callable, optional
1667 A callable that takes a string, used (possibly repeatedly) to
1668 report inequalities.
1669
1670 Returns
1671 -------
1672 isEqual : `bool`
1673 `True` when the two `lsst.pex.config.Config` instances are equal.
1674 `False` if there is an inequality.
1675
1676 See Also
1677 --------
1678 lsst.pex.config.compareConfigs
1679
1680 Notes
1681 -----
1682 Unselected targets of `~lsst.pex.config.RegistryField` fields and
1683 unselected choices of `~lsst.pex.config.ConfigChoiceField` fields
1684 are not considered by this method.
1685
1686 Floating point comparisons are performed by `numpy.allclose`.
1687 """
1688 name1 = self._name if self._name is not None else "config"
1689 name2 = other._name if other._name is not None else "config"
1690 name = getComparisonName(name1, name2)
1691 return compareConfigs(name, self, other, shortcut=shortcut, rtol=rtol, atol=atol, output=output)
1692

◆ copy()

Config lsst.pex.config.config.Config.copy ( self)
inherited
Return a deep copy of this config.

Notes
-----
The returned config object is not frozen, even if the original was.
If a nested config object is copied, it retains the name from its
original hierarchy.

Nested objects are only shared between the new and old configs if they
are not possible to modify via the config's interfaces (e.g. entries
in the the history list are not copied, but the lists themselves are,
so modifications to one copy do not modify the other).

Reimplemented in lsst.pex.config.configurableActions._configurableAction.ConfigurableAction.

Definition at line 1066 of file config.py.

1066 def copy(self) -> Config:
1067 """Return a deep copy of this config.
1068
1069 Notes
1070 -----
1071 The returned config object is not frozen, even if the original was.
1072 If a nested config object is copied, it retains the name from its
1073 original hierarchy.
1074
1075 Nested objects are only shared between the new and old configs if they
1076 are not possible to modify via the config's interfaces (e.g. entries
1077 in the the history list are not copied, but the lists themselves are,
1078 so modifications to one copy do not modify the other).
1079 """
1080 instance = object.__new__(type(self))
1081 instance._frozen = False
1082 instance._name = self._name
1083 instance._history = {k: list(v) for k, v in self._history.items()}
1084 instance._imports = set(self._imports)
1085 # Important to set up storage last, since fields sometimes store
1086 # proxy objects that reference their parent (especially for history).
1087 instance._storage = {k: self._fields[k]._copy_storage(self, instance) for k in self._storage}
1088 return instance
1089

◆ formatHistory()

lsst.pex.config.config.Config.formatHistory ( self,
name,
** kwargs )
inherited
Format a configuration field's history to a human-readable format.

Parameters
----------
name : `str`
    Name of a `~lsst.pex.config.Field` in this config.
**kwargs
    Keyword arguments passed to `lsst.pex.config.history.format`.

Returns
-------
history : `str`
    A string containing the formatted history.

See Also
--------
lsst.pex.config.history.format

Definition at line 1555 of file config.py.

1555 def formatHistory(self, name, **kwargs):
1556 """Format a configuration field's history to a human-readable format.
1557
1558 Parameters
1559 ----------
1560 name : `str`
1561 Name of a `~lsst.pex.config.Field` in this config.
1562 **kwargs
1563 Keyword arguments passed to `lsst.pex.config.history.format`.
1564
1565 Returns
1566 -------
1567 history : `str`
1568 A string containing the formatted history.
1569
1570 See Also
1571 --------
1572 lsst.pex.config.history.format
1573 """
1574 import lsst.pex.config.history as pexHist
1575
1576 return pexHist.format(self, name, **kwargs)
1577

◆ freeze()

lsst.pex.config.configChoiceField.ConfigChoiceField.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 597 of file configChoiceField.py.

597 def freeze(self, instance):
598 instanceDict = self.__get__(instance)
599 instanceDict.freeze()
600 for v in instanceDict.values():
601 v.freeze()
602

◆ items()

lsst.pex.config.config.Config.items ( self)
inherited
Get configurations as ``(field name, field value)`` pairs.

Returns
-------
items : `~collections.abc.ItemsView`
    Iterator of tuples for each configuration. Tuple items are:

    0. Field name.
    1. Field value.

Definition at line 1005 of file config.py.

1005 def items(self):
1006 """Get configurations as ``(field name, field value)`` pairs.
1007
1008 Returns
1009 -------
1010 items : `~collections.abc.ItemsView`
1011 Iterator of tuples for each configuration. Tuple items are:
1012
1013 0. Field name.
1014 1. Field value.
1015 """
1016 return self._storage.items()
1017

◆ keys()

lsst.pex.config.config.Config.keys ( self)
inherited
Get field names.

Returns
-------
names : `~collections.abc.KeysView`
    List of `lsst.pex.config.Field` names.

Definition at line 985 of file config.py.

985 def keys(self):
986 """Get field names.
987
988 Returns
989 -------
990 names : `~collections.abc.KeysView`
991 List of `lsst.pex.config.Field` names.
992 """
993 return self._storage.keys()
994

◆ load()

lsst.pex.config.config.Config.load ( self,
filename,
root = "config" )
inherited
Modify this config in place by executing the Python code in a
configuration file.

Parameters
----------
filename : `str`
    Name of the configuration file. A configuration file is Python
    module.
root : `str`, optional
    Name of the variable in file that refers to the config being
    overridden.

    For example, the value of root is ``"config"`` and the file
    contains::

        config.myField = 5

    Then this config's field ``myField`` is set to ``5``.

See Also
--------
lsst.pex.config.Config.loadFromStream
lsst.pex.config.Config.loadFromString
lsst.pex.config.Config.save
lsst.pex.config.Config.saveToStream
lsst.pex.config.Config.saveToString

Definition at line 1174 of file config.py.

1174 def load(self, filename, root="config"):
1175 """Modify this config in place by executing the Python code in a
1176 configuration file.
1177
1178 Parameters
1179 ----------
1180 filename : `str`
1181 Name of the configuration file. A configuration file is Python
1182 module.
1183 root : `str`, optional
1184 Name of the variable in file that refers to the config being
1185 overridden.
1186
1187 For example, the value of root is ``"config"`` and the file
1188 contains::
1189
1190 config.myField = 5
1191
1192 Then this config's field ``myField`` is set to ``5``.
1193
1194 See Also
1195 --------
1196 lsst.pex.config.Config.loadFromStream
1197 lsst.pex.config.Config.loadFromString
1198 lsst.pex.config.Config.save
1199 lsst.pex.config.Config.saveToStream
1200 lsst.pex.config.Config.saveToString
1201 """
1202 with open(filename) as f:
1203 code = compile(f.read(), filename=filename, mode="exec")
1204 self.loadFromString(code, root=root, filename=filename)
1205

◆ loadFromStream()

lsst.pex.config.config.Config.loadFromStream ( self,
stream,
root = "config",
filename = None,
extraLocals = None )
inherited
Modify this Config in place by executing the Python code in the
provided stream.

Parameters
----------
stream : file-like object, `str`, `bytes`, or `~types.CodeType`
    Stream containing configuration override code.  If this is a
    code object, it should be compiled with ``mode="exec"``.
root : `str`, optional
    Name of the variable in file that refers to the config being
    overridden.

    For example, the value of root is ``"config"`` and the file
    contains::

        config.myField = 5

    Then this config's field ``myField`` is set to ``5``.
filename : `str`, optional
    Name of the configuration file, or `None` if unknown or contained
    in the stream. Used for error reporting.
extraLocals : `dict` of `str` to `object`, optional
    Any extra variables to include in local scope when loading.

Notes
-----
For backwards compatibility reasons, this method accepts strings, bytes
and code objects as well as file-like objects.  New code should use
`loadFromString` instead for most of these types.

See Also
--------
lsst.pex.config.Config.load
lsst.pex.config.Config.loadFromString
lsst.pex.config.Config.save
lsst.pex.config.Config.saveToStream
lsst.pex.config.Config.saveToString

Definition at line 1206 of file config.py.

1206 def loadFromStream(self, stream, root="config", filename=None, extraLocals=None):
1207 """Modify this Config in place by executing the Python code in the
1208 provided stream.
1209
1210 Parameters
1211 ----------
1212 stream : file-like object, `str`, `bytes`, or `~types.CodeType`
1213 Stream containing configuration override code. If this is a
1214 code object, it should be compiled with ``mode="exec"``.
1215 root : `str`, optional
1216 Name of the variable in file that refers to the config being
1217 overridden.
1218
1219 For example, the value of root is ``"config"`` and the file
1220 contains::
1221
1222 config.myField = 5
1223
1224 Then this config's field ``myField`` is set to ``5``.
1225 filename : `str`, optional
1226 Name of the configuration file, or `None` if unknown or contained
1227 in the stream. Used for error reporting.
1228 extraLocals : `dict` of `str` to `object`, optional
1229 Any extra variables to include in local scope when loading.
1230
1231 Notes
1232 -----
1233 For backwards compatibility reasons, this method accepts strings, bytes
1234 and code objects as well as file-like objects. New code should use
1235 `loadFromString` instead for most of these types.
1236
1237 See Also
1238 --------
1239 lsst.pex.config.Config.load
1240 lsst.pex.config.Config.loadFromString
1241 lsst.pex.config.Config.save
1242 lsst.pex.config.Config.saveToStream
1243 lsst.pex.config.Config.saveToString
1244 """
1245 if hasattr(stream, "read"):
1246 if filename is None:
1247 filename = getattr(stream, "name", "?")
1248 code = compile(stream.read(), filename=filename, mode="exec")
1249 else:
1250 code = stream
1251 self.loadFromString(code, root=root, filename=filename, extraLocals=extraLocals)
1252

◆ loadFromString()

lsst.pex.config.config.Config.loadFromString ( self,
code,
root = "config",
filename = None,
extraLocals = None )
inherited
Modify this Config in place by executing the Python code in the
provided string.

Parameters
----------
code : `str`, `bytes`, or `~types.CodeType`
    Stream containing configuration override code.
root : `str`, optional
    Name of the variable in file that refers to the config being
    overridden.

    For example, the value of root is ``"config"`` and the file
    contains::

        config.myField = 5

    Then this config's field ``myField`` is set to ``5``.
filename : `str`, optional
    Name of the configuration file, or `None` if unknown or contained
    in the stream. Used for error reporting.
extraLocals : `dict` of `str` to `object`, optional
    Any extra variables to include in local scope when loading.

Raises
------
ValueError
    Raised if a key in extraLocals is the same value as the value of
    the root argument.

See Also
--------
lsst.pex.config.Config.load
lsst.pex.config.Config.loadFromStream
lsst.pex.config.Config.save
lsst.pex.config.Config.saveToStream
lsst.pex.config.Config.saveToString

Definition at line 1253 of file config.py.

1253 def loadFromString(self, code, root="config", filename=None, extraLocals=None):
1254 """Modify this Config in place by executing the Python code in the
1255 provided string.
1256
1257 Parameters
1258 ----------
1259 code : `str`, `bytes`, or `~types.CodeType`
1260 Stream containing configuration override code.
1261 root : `str`, optional
1262 Name of the variable in file that refers to the config being
1263 overridden.
1264
1265 For example, the value of root is ``"config"`` and the file
1266 contains::
1267
1268 config.myField = 5
1269
1270 Then this config's field ``myField`` is set to ``5``.
1271 filename : `str`, optional
1272 Name of the configuration file, or `None` if unknown or contained
1273 in the stream. Used for error reporting.
1274 extraLocals : `dict` of `str` to `object`, optional
1275 Any extra variables to include in local scope when loading.
1276
1277 Raises
1278 ------
1279 ValueError
1280 Raised if a key in extraLocals is the same value as the value of
1281 the root argument.
1282
1283 See Also
1284 --------
1285 lsst.pex.config.Config.load
1286 lsst.pex.config.Config.loadFromStream
1287 lsst.pex.config.Config.save
1288 lsst.pex.config.Config.saveToStream
1289 lsst.pex.config.Config.saveToString
1290 """
1291 if filename is None:
1292 # try to determine the file name; a compiled string
1293 # has attribute "co_filename",
1294 filename = getattr(code, "co_filename", "?")
1295 with RecordingImporter() as importer:
1296 globals = {"__file__": filename}
1297 local = {root: self}
1298 if extraLocals is not None:
1299 # verify the value of root was not passed as extra local args
1300 if root in extraLocals:
1301 raise ValueError(
1302 f"{root} is reserved and cannot be used as a variable name in extraLocals"
1303 )
1304 local.update(extraLocals)
1305 exec(code, globals, local)
1306
1307 self._imports.update(importer.getModules())
1308

◆ rename()

lsst.pex.config.configChoiceField.ConfigChoiceField.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 564 of file configChoiceField.py.

564 def rename(self, instance):
565 instanceDict = self.__get__(instance)
566 fullname = _joinNamePath(instance._name, self.name)
567 instanceDict._rename(fullname)
568

◆ save()

lsst.pex.config.configChoiceField.ConfigChoiceField.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 609 of file configChoiceField.py.

609 def save(self, outfile, instance):
610 instanceDict = self.__get__(instance)
611 fullname = _joinNamePath(instance._name, self.name)
612 for v in instanceDict.values():
613 v._save(outfile)
614 if self.multi:
615 outfile.write(f"{fullname}.names={sorted(instanceDict.names)!r}\n")
616 else:
617 outfile.write(f"{fullname}.name={instanceDict.name!r}\n")
618

◆ saveToStream()

lsst.pex.config.config.Config.saveToStream ( self,
outfile,
root = "config",
skipImports = False )
inherited
Save a configuration file to a stream, which, when loaded,
reproduces this config.

Parameters
----------
outfile : file-like object
    Destination file object write the config into. Accepts strings not
    bytes.
root : `str`, optional
    Name to use for the root config variable. The same value must be
    used when loading (see `lsst.pex.config.Config.load`).
skipImports : `bool`, optional
    If `True` then do not include ``import`` statements in output,
    this is to support human-oriented output from ``pipetask`` where
    additional clutter is not useful.

See Also
--------
lsst.pex.config.Config.save
lsst.pex.config.Config.saveToString
lsst.pex.config.Config.load
lsst.pex.config.Config.loadFromStream
lsst.pex.config.Config.loadFromString

Definition at line 1371 of file config.py.

1371 def saveToStream(self, outfile, root="config", skipImports=False):
1372 """Save a configuration file to a stream, which, when loaded,
1373 reproduces this config.
1374
1375 Parameters
1376 ----------
1377 outfile : file-like object
1378 Destination file object write the config into. Accepts strings not
1379 bytes.
1380 root : `str`, optional
1381 Name to use for the root config variable. The same value must be
1382 used when loading (see `lsst.pex.config.Config.load`).
1383 skipImports : `bool`, optional
1384 If `True` then do not include ``import`` statements in output,
1385 this is to support human-oriented output from ``pipetask`` where
1386 additional clutter is not useful.
1387
1388 See Also
1389 --------
1390 lsst.pex.config.Config.save
1391 lsst.pex.config.Config.saveToString
1392 lsst.pex.config.Config.load
1393 lsst.pex.config.Config.loadFromStream
1394 lsst.pex.config.Config.loadFromString
1395 """
1396 tmp = self._name
1397 self._rename(root)
1398 try:
1399 if not skipImports:
1400 self._collectImports()
1401 # Remove self from the set, as it is handled explicitly below
1402 self._imports.remove(self.__module__)
1403 configType = type(self)
1404 typeString = _typeStr(configType)
1405 outfile.write(f"import {configType.__module__}\n")
1406 # We are required to write this on a single line because
1407 # of later regex matching, rather than adopting black style
1408 # formatting.
1409 outfile.write(
1410 f'assert type({root}) is {typeString}, f"config is of type '
1411 f'{{type({root}).__module__}}.{{type({root}).__name__}} instead of {typeString}"\n\n'
1412 )
1413 for imp in sorted(self._imports):
1414 if imp in sys.modules and sys.modules[imp] is not None:
1415 outfile.write(f"import {imp}\n")
1416 self._save(outfile)
1417 finally:
1418 self._rename(tmp)
1419

◆ saveToString()

lsst.pex.config.config.Config.saveToString ( self,
skipImports = False )
inherited
Return the Python script form of this configuration as an executable
string.

Parameters
----------
skipImports : `bool`, optional
    If `True` then do not include ``import`` statements in output,
    this is to support human-oriented output from ``pipetask`` where
    additional clutter is not useful.

Returns
-------
code : `str`
    A code string readable by `loadFromString`.

See Also
--------
lsst.pex.config.Config.save
lsst.pex.config.Config.saveToStream
lsst.pex.config.Config.load
lsst.pex.config.Config.loadFromStream
lsst.pex.config.Config.loadFromString

Definition at line 1343 of file config.py.

1343 def saveToString(self, skipImports=False):
1344 """Return the Python script form of this configuration as an executable
1345 string.
1346
1347 Parameters
1348 ----------
1349 skipImports : `bool`, optional
1350 If `True` then do not include ``import`` statements in output,
1351 this is to support human-oriented output from ``pipetask`` where
1352 additional clutter is not useful.
1353
1354 Returns
1355 -------
1356 code : `str`
1357 A code string readable by `loadFromString`.
1358
1359 See Also
1360 --------
1361 lsst.pex.config.Config.save
1362 lsst.pex.config.Config.saveToStream
1363 lsst.pex.config.Config.load
1364 lsst.pex.config.Config.loadFromStream
1365 lsst.pex.config.Config.loadFromString
1366 """
1367 buffer = io.StringIO()
1368 self.saveToStream(buffer, skipImports=skipImports)
1369 return buffer.getvalue()
1370

◆ setDefaults()

lsst.pex.config.config.Config.setDefaults ( self)
inherited
Subclass hook for computing defaults.

Notes
-----
Derived `~lsst.pex.config.Config` classes that must compute defaults
rather than using the `~lsst.pex.config.Field` instances's defaults
should do so here. To correctly use inherited defaults,
implementations of ``setDefaults`` must call their base class's
``setDefaults``.

Reimplemented in lsst.pipe.tasks.background.MaskObjectsConfig, lsst.pipe.tasks.dataFrameActions._actions.NanoJansky, lsst.pipe.tasks.measurementDriver.ForcedMeasurementDriverConfig, lsst.ip.diffim.dipoleMeasurement.DipoleMeasurementConfig, lsst.ip.diffim.subtractImages.AlardLuptonSubtractBaseConfig, lsst.ip.isr.ampOffset.AmpOffsetConfig, lsst.meas.algorithms.computeExPsf.ComputeExPsfConfig, lsst.meas.algorithms.measureApCorr.MeasureApCorrConfig, lsst.meas.algorithms.noise_covariance.ComputeNoiseCorrelationConfig, lsst.meas.algorithms.normalizedCalibrationFlux.NormalizedCalibrationFluxConfig, lsst.meas.algorithms.scaleVariance.ScaleVarianceConfig, lsst.meas.base.forcedMeasurement.ForcedMeasurementConfig, lsst.meas.base.simple_forced_measurement.SimpleForcedMeasurementConfig, lsst.meas.modelfit.cmodel.cmodelContinued.CModelForcedConfig, lsst.meas.modelfit.cmodel.cmodelContinued.CModelSingleFrameConfig, lsst.meas.modelfit.psf.psfContinued.GeneralShapeletPsfApproxForcedConfig, and lsst.meas.modelfit.psf.psfContinued.GeneralShapeletPsfApproxSingleFrameConfig.

Definition at line 1103 of file config.py.

1103 def setDefaults(self):
1104 """Subclass hook for computing defaults.
1105
1106 Notes
1107 -----
1108 Derived `~lsst.pex.config.Config` classes that must compute defaults
1109 rather than using the `~lsst.pex.config.Field` instances's defaults
1110 should do so here. To correctly use inherited defaults,
1111 implementations of ``setDefaults`` must call their base class's
1112 ``setDefaults``.
1113 """
1114 pass
1115

◆ toDict()

lsst.pex.config.configChoiceField.ConfigChoiceField.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 581 of file configChoiceField.py.

581 def toDict(self, instance):
582 instanceDict = self.__get__(instance)
583
584 dict_ = {}
585 if self.multi:
586 dict_["names"] = instanceDict.names
587 else:
588 dict_["name"] = instanceDict.name
589
590 values = {}
591 for k, v in instanceDict.items():
592 values[k] = v.toDict()
593 dict_["values"] = values
594
595 return dict_
596

◆ types()

lsst.pex.config.configChoiceField.ConfigInstanceDict.types ( self)
inherited

Definition at line 201 of file configChoiceField.py.

201 def types(self):
202 return self._typemap if self._typemap is not None else self._field.typemap
203

◆ update()

lsst.pex.config.config.Config.update ( self,
** kw )
inherited
Update values of fields specified by the keyword arguments.

Parameters
----------
**kw
    Keywords are configuration field names. Values are configuration
    field values.

Notes
-----
The ``__at`` and ``__label`` keyword arguments are special internal
keywords. They are used to strip out any internal steps from the
history tracebacks of the config. Do not modify these keywords to
subvert a `~lsst.pex.config.Config` instance's history.

Examples
--------
This is a config with three fields:

>>> from lsst.pex.config import Config, Field
>>> class DemoConfig(Config):
...     fieldA = Field(doc="Field A", dtype=int, default=42)
...     fieldB = Field(doc="Field B", dtype=bool, default=True)
...     fieldC = Field(doc="Field C", dtype=str, default="Hello world")
>>> config = DemoConfig()

These are the default values of each field:

>>> for name, value in config.iteritems():
...     print(f"{name}: {value}")
fieldA: 42
fieldB: True
fieldC: 'Hello world'

Using this method to update ``fieldA`` and ``fieldC``:

>>> config.update(fieldA=13, fieldC="Updated!")

Now the values of each field are:

>>> for name, value in config.iteritems():
...     print(f"{name}: {value}")
fieldA: 13
fieldB: True
fieldC: 'Updated!'

Definition at line 1116 of file config.py.

1116 def update(self, **kw):
1117 """Update values of fields specified by the keyword arguments.
1118
1119 Parameters
1120 ----------
1121 **kw
1122 Keywords are configuration field names. Values are configuration
1123 field values.
1124
1125 Notes
1126 -----
1127 The ``__at`` and ``__label`` keyword arguments are special internal
1128 keywords. They are used to strip out any internal steps from the
1129 history tracebacks of the config. Do not modify these keywords to
1130 subvert a `~lsst.pex.config.Config` instance's history.
1131
1132 Examples
1133 --------
1134 This is a config with three fields:
1135
1136 >>> from lsst.pex.config import Config, Field
1137 >>> class DemoConfig(Config):
1138 ... fieldA = Field(doc="Field A", dtype=int, default=42)
1139 ... fieldB = Field(doc="Field B", dtype=bool, default=True)
1140 ... fieldC = Field(doc="Field C", dtype=str, default="Hello world")
1141 >>> config = DemoConfig()
1142
1143 These are the default values of each field:
1144
1145 >>> for name, value in config.iteritems():
1146 ... print(f"{name}: {value}")
1147 fieldA: 42
1148 fieldB: True
1149 fieldC: 'Hello world'
1150
1151 Using this method to update ``fieldA`` and ``fieldC``:
1152
1153 >>> config.update(fieldA=13, fieldC="Updated!")
1154
1155 Now the values of each field are:
1156
1157 >>> for name, value in config.iteritems():
1158 ... print(f"{name}: {value}")
1159 fieldA: 13
1160 fieldB: True
1161 fieldC: 'Updated!'
1162 """
1163 at = kw.pop("__at", getCallStack())
1164 label = kw.pop("__label", "update")
1165
1166 for name, value in kw.items():
1167 try:
1168 field = self._fields[name]
1169 field.__set__(self, value, at=at, label=label)
1170 except KeyError as e:
1171 e.add_note(f"No field of name {name} exists in config type {_typeStr(self)}")
1172 raise
1173

◆ validate()

lsst.pex.config.configChoiceField.ConfigChoiceField.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 569 of file configChoiceField.py.

569 def validate(self, instance):
570 instanceDict = self.__get__(instance)
571 if instanceDict.active is None and not self.optional:
572 msg = "Required field cannot be None"
573 raise FieldValidationError(self, instance, msg)
574 elif instanceDict.active is not None:
575 if self.multi:
576 for a in instanceDict.active:
577 a.validate()
578 else:
579 instanceDict.active.validate()
580

◆ values()

lsst.pex.config.config.Config.values ( self)
inherited
Get field values.

Returns
-------
values : `~collections.abc.ValuesView`
    Iterator of field values.

Definition at line 995 of file config.py.

995 def values(self):
996 """Get field values.
997
998 Returns
999 -------
1000 values : `~collections.abc.ValuesView`
1001 Iterator of field values.
1002 """
1003 return self._storage.values()
1004

Member Data Documentation

◆ _config

lsst.pex.config.configChoiceField.ConfigInstanceDict._config = config
protectedinherited

Definition at line 182 of file configChoiceField.py.

◆ _dict

dict lsst.pex.config.configChoiceField.ConfigInstanceDict._dict = {}
protectedinherited

Definition at line 180 of file configChoiceField.py.

◆ _field

lsst.pex.config.configChoiceField.ConfigInstanceDict._field = field
protectedinherited

Definition at line 183 of file configChoiceField.py.

◆ _fields

dict lsst.pex.config.config.ConfigMeta._fields = {}
protectedinherited

Definition at line 228 of file config.py.

◆ _frozen

bool lsst.pex.config.config.Config._frozen = True
protectedinherited

Definition at line 1422 of file config.py.

◆ _history

dict lsst.pex.config.config.Config._history [str, list[Any]]
staticprotectedinherited

Definition at line 978 of file config.py.

◆ _imports

lsst.pex.config.config.Config._imports [Any]
staticprotectedinherited

Definition at line 979 of file config.py.

◆ _name

lsst.pex.config.config.Config._name = name
protectedinherited

Definition at line 1525 of file config.py.

◆ _selection

lsst.pex.config.configChoiceField.ConfigInstanceDict._selection = None
protectedinherited

Definition at line 181 of file configChoiceField.py.

◆ _source

lsst.pex.config.config.ConfigMeta._source = getStackFrame()
protectedinherited

Definition at line 229 of file config.py.

◆ _storage

dict lsst.pex.config.config.Config._storage [str, Any]
staticprotectedinherited

Definition at line 976 of file config.py.

◆ _typemap

lsst.pex.config.configChoiceField.ConfigInstanceDict._typemap = None
protectedinherited

Definition at line 186 of file configChoiceField.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.

◆ instanceDictClass

lsst.pex.config.configChoiceField.ConfigChoiceField.instanceDictClass = ConfigInstanceDict
static

Definition at line 494 of file configChoiceField.py.

◆ multi

lsst.pex.config.configChoiceField.ConfigChoiceField.multi = multi

Definition at line 508 of file configChoiceField.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.

◆ typemap

lsst.pex.config.configChoiceField.ConfigChoiceField.typemap = typemap

Definition at line 507 of file configChoiceField.py.

◆ types

lsst.pex.config.configChoiceField.ConfigInstanceDict.types
inherited

Definition at line 208 of file configChoiceField.py.

Property Documentation

◆ active

lsst.pex.config.configChoiceField.ConfigInstanceDict.active = property(_getActive)
staticinherited

Definition at line 293 of file configChoiceField.py.

◆ history

lsst.pex.config.config.Config.history = property(lambda x: x._history)
staticinherited

Definition at line 1578 of file config.py.

◆ name

lsst.pex.config.configChoiceField.ConfigInstanceDict.name = property(_getName, _setName, _delName)
staticinherited

Definition at line 278 of file configChoiceField.py.

◆ names

lsst.pex.config.configChoiceField.ConfigInstanceDict.names = property(_getNames, _setNames, _delNames)
staticinherited

Definition at line 272 of file configChoiceField.py.


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