LSST Applications g0fba68d861+bb7a7cfa1f,g1ec0fe41b4+f536777771,g1fd858c14a+470a99fdf4,g216c3ac8a7+0d4d80193f,g35bb328faa+fcb1d3bbc8,g4d2262a081+23bd310d1b,g53246c7159+fcb1d3bbc8,g56a49b3a55+369644a549,g5a012ec0e7+3632fc3ff3,g60b5630c4e+3bfb9058a5,g67b6fd64d1+ed4b5058f4,g78460c75b0+2f9a1b4bcd,g786e29fd12+cf7ec2a62a,g8180f54f50+60bd39f3b6,g8352419a5c+fcb1d3bbc8,g87d29937c9+57a68d035f,g8852436030+4699110379,g89139ef638+ed4b5058f4,g9125e01d80+fcb1d3bbc8,g94187f82dc+3bfb9058a5,g989de1cb63+ed4b5058f4,g9ccd5d7f00+b7cae620c0,g9d31334357+3bfb9058a5,g9f33ca652e+00883ace41,gabe3b4be73+1e0a283bba,gabf8522325+fa80ff7197,gb1101e3267+27b24065a3,gb58c049af0+f03b321e39,gb89ab40317+ed4b5058f4,gc0af124501+708fe67c54,gcf25f946ba+4699110379,gd6cbbdb0b4+bb83cc51f8,gde0f65d7ad+acd5afb0eb,ge1ad929117+3bfb9058a5,ge278dab8ac+d65b3c2b70,ge410e46f29+ed4b5058f4,gf5e32f922b+fcb1d3bbc8,gf67bdafdda+ed4b5058f4,w.2025.17
LSST Data Management Base Package
Loading...
Searching...
No Matches
lsst.pex.config.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)
 
 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")
 
 _collectImports (self, instance, imports)
 
 _compare (self, instance1, instance2, shortcut, rtol, atol, output)
 
 _setup (self, doc, dtype, default, check, optional, source, deprecated)
 
 _validateValue (self, value)
 
 _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 381 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 486 of file configChoiceField.py.

486 def __init__(self, doc, typemap, default=None, optional=False, multi=False, deprecated=None):
487 source = getStackFrame()
488 self._setup(
489 doc=doc,
490 dtype=self.instanceDictClass,
491 default=default,
492 check=None,
493 optional=optional,
494 source=source,
495 deprecated=deprecated,
496 )
497 self.typemap = typemap
498 self.multi = multi
499

Member Function Documentation

◆ __class_getitem__()

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

Definition at line 500 of file configChoiceField.py.

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

◆ __contains__()

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

Definition at line 194 of file configChoiceField.py.

194 def __contains__(self, k):
195 return k in self.types
196

◆ __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 602 of file configChoiceField.py.

602 def __deepcopy__(self, memo):
603 """Customize deep-copying, because we always want a reference to the
604 original typemap.
605
606 WARNING: this must be overridden by subclasses if they change the
607 constructor signature!
608 """
609 other = type(self)(
610 doc=self.doc,
611 typemap=self.typemap,
612 default=copy.deepcopy(self.default),
613 optional=self.optional,
614 multi=self.multi,
615 )
616 other.source = self.source
617 return other
618

◆ __delattr__()

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

Definition at line 1585 of file config.py.

1585 def __delattr__(self, attr, at=None, label="deletion"):
1586 if attr in self._fields:
1587 if at is None:
1588 at = getCallStack()
1589 self._fields[attr].__delete__(self, at=at, label=label)
1590 else:
1591 object.__delattr__(self, attr)
1592

◆ __delete__()

lsst.pex.config.config.Field.__delete__ ( self,
instance,
at = None,
label = "deletion" )
inherited
Delete an attribute from a `lsst.pex.config.Config` instance.

Parameters
----------
instance : `lsst.pex.config.Config`
    The config instance that contains this field.
at : `list` of `lsst.pex.config.callStack.StackFrame`
    The call stack (created by
    `lsst.pex.config.callStack.getCallStack`).
label : `str`, optional
    Event label for the history.

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

Definition at line 800 of file config.py.

800 def __delete__(self, instance, at=None, label="deletion"):
801 """Delete an attribute from a `lsst.pex.config.Config` instance.
802
803 Parameters
804 ----------
805 instance : `lsst.pex.config.Config`
806 The config instance that contains this field.
807 at : `list` of `lsst.pex.config.callStack.StackFrame`
808 The call stack (created by
809 `lsst.pex.config.callStack.getCallStack`).
810 label : `str`, optional
811 Event label for the history.
812
813 Notes
814 -----
815 This is invoked by the owning `~lsst.pex.config.Config` object and
816 should not be called directly.
817 """
818 if at is None:
819 at = getCallStack()
820 self.__set__(instance, None, at=at, label=label)
821

◆ __eq__()

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

Definition at line 1593 of file config.py.

1593 def __eq__(self, other):
1594 if type(other) is type(self):
1595 for name in self._fields:
1596 thisValue = getattr(self, name)
1597 otherValue = getattr(other, name)
1598 if isinstance(thisValue, float) and math.isnan(thisValue):
1599 if not math.isnan(otherValue):
1600 return False
1601 elif thisValue != otherValue:
1602 return False
1603 return True
1604 return False
1605

◆ __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 521 of file configChoiceField.py.

523 ) -> ConfigInstanceDict: ...
524

◆ __get__() [2/3]

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

Definition at line 525 of file configChoiceField.py.

525 def __get__(self, instance, owner=None, at=None, label="default"):
526 if instance is None or not isinstance(instance, Config):
527 return self
528 else:
529 return self._getOrMake(instance)
530

◆ __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 516 of file configChoiceField.py.

518 ) -> ConfigChoiceField: ...
519

◆ __getitem__()

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

Definition at line 290 of file configChoiceField.py.

290 def __getitem__(self, k, at=None, label="default"):
291 try:
292 value = self._dict[k]
293 except KeyError:
294 try:
295 dtype = self.types[k]
296 except Exception as e:
297 raise FieldValidationError(
298 self._field, self._config, f"Unknown key {k!r} in Registry/ConfigChoiceField"
299 ) from e
300 name = _joinNamePath(self._config._name, self._field.name, k)
301 if at is None:
302 at = getCallStack()
303 at.insert(0, dtype._source)
304 value = self._dict.setdefault(k, dtype(__name=name, __at=at, __label=label))
305 return value
306

◆ __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 1662 of file config.py.

1662 def __init_subclass__(cls, **kwargs):
1663 """Run initialization for every subclass.
1664
1665 Specifically registers the subclass with a YAML representer
1666 and YAML constructor (if pyyaml is available)
1667 """
1668 super().__init_subclass__(**kwargs)
1669
1670 if not yaml:
1671 return
1672
1673 yaml.add_representer(cls, _yaml_config_representer)
1674

◆ __iter__()

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

Definition at line 200 of file configChoiceField.py.

200 def __iter__(self):
201 return iter(self.types)
202

◆ __len__()

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

Definition at line 197 of file configChoiceField.py.

197 def __len__(self):
198 return len(self.types)
199

◆ __ne__()

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

Definition at line 1606 of file config.py.

1606 def __ne__(self, other):
1607 return not self.__eq__(other)
1608

◆ __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 1025 of file config.py.

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

◆ __reduce__()

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

Definition at line 373 of file configChoiceField.py.

373 def __reduce__(self):
374 raise UnexpectedProxyUsageError(
375 f"Proxy container for config field {self._field.name} cannot "
376 "be pickled; it should be converted to a built-in container before "
377 "being assigned to other objects or variables."
378 )
379
380

◆ __repr__()

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

Definition at line 1612 of file config.py.

1612 def __repr__(self):
1613 return "{}({})".format(
1614 _typeStr(self),
1615 ", ".join(f"{k}={v!r}" for k, v in self.toDict().items() if v is not None),
1616 )
1617

◆ __set__()

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

Definition at line 531 of file configChoiceField.py.

533 ) -> None:
534 if instance._frozen:
535 raise FieldValidationError(self, instance, "Cannot modify a frozen Config")
536 if at is None:
537 at = getCallStack()
538 instanceDict = self._getOrMake(instance)
539 if isinstance(value, self.instanceDictClass):
540 for k, v in value.items():
541 instanceDict.__setitem__(k, v, at=at, label=label)
542 instanceDict._setSelection(value._selection, at=at, label=label)
543
544 else:
545 instanceDict._setSelection(value, at=at, label=label)
546

◆ __setattr__()

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

Definition at line 341 of file configChoiceField.py.

341 def __setattr__(self, attr, value, at=None, label="assignment"):
342 if hasattr(getattr(self.__class__, attr, None), "__set__"):
343 # This allows properties to work.
344 object.__setattr__(self, attr, value)
345 elif attr in self.__dict__ or attr in [
346 "_history",
347 "_field",
348 "_config",
349 "_dict",
350 "_selection",
351 "__doc__",
352 "_typemap",
353 ]:
354 # This allows specific private attributes to work.
355 object.__setattr__(self, attr, value)
356 else:
357 # We throw everything else.
358 msg = f"{_typeStr(self._field)} has no attribute {attr}"
359 raise FieldValidationError(self._field, self._config, msg)
360

◆ __setitem__()

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

Definition at line 307 of file configChoiceField.py.

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

◆ __str__()

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

Definition at line 1609 of file config.py.

1609 def __str__(self):
1610 return str(self.toDict())
1611

◆ _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 586 of file configChoiceField.py.

586 def _collectImports(self, instance, imports):
587 instanceDict = self.__get__(instance)
588 for config in instanceDict.values():
589 config._collectImports()
590 imports |= config._imports
591

◆ _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 619 of file configChoiceField.py.

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

◆ _delName()

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

Definition at line 255 of file configChoiceField.py.

255 def _delName(self):
256 if self._field.multi:
257 raise FieldValidationError(
258 self._field, self._config, "Multi-selection field has no attribute 'name'"
259 )
260 self._selection = None
261

◆ _delNames()

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

Definition at line 234 of file configChoiceField.py.

234 def _delNames(self):
235 if not self._field.multi:
236 raise FieldValidationError(
237 self._field, self._config, "Single-selection field has no attribute 'names'"
238 )
239 self._selection = None
240

◆ _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 1676 of file config.py.

1676 def _fromPython(cls, config_py):
1677 """Instantiate a `Config`-subclass from serialized Python form.
1678
1679 Parameters
1680 ----------
1681 config_py : `str`
1682 A serialized form of the Config as created by
1683 `Config.saveToStream`.
1684
1685 Returns
1686 -------
1687 config : `Config`
1688 Reconstructed `Config` instant.
1689 """
1690 cls = _classFromPython(config_py)
1691 return unreduceConfig(cls, config_py)
1692
1693

◆ _getActive()

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

Definition at line 274 of file configChoiceField.py.

274 def _getActive(self):
275 if self._selection is None:
276 return None
277
278 if self._field.multi:
279 return [self[c] for c in self._selection]
280 else:
281 return self[self._selection]
282

◆ _getName()

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

Definition at line 241 of file configChoiceField.py.

241 def _getName(self):
242 if self._field.multi:
243 raise FieldValidationError(
244 self._field, self._config, "Multi-selection field has no attribute 'name'"
245 )
246 return self._selection
247

◆ _getNames()

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

Definition at line 220 of file configChoiceField.py.

220 def _getNames(self):
221 if not self._field.multi:
222 raise FieldValidationError(
223 self._field, self._config, "Single-selection field has no attribute 'names'"
224 )
225 return self._selection
226

◆ _getOrMake()

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

Definition at line 503 of file configChoiceField.py.

503 def _getOrMake(self, instance, label="default"):
504 instanceDict = instance._storage.get(self.name)
505 if instanceDict is None:
506 at = getCallStack(1)
507 instanceDict = self.dtype(instance, self)
508 instanceDict.__doc__ = self.doc
509 instance._storage[self.name] = instanceDict
510 history = instance._history.setdefault(self.name, [])
511 history.append(("Initialized from defaults", at, label))
512
513 return instanceDict
514

◆ _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 337 of file configChoiceField.py.

337 def _rename(self, fullname):
338 for k, v in self._dict.items():
339 v._rename(_joinNamePath(name=fullname, index=k))
340

◆ _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 1394 of file config.py.

1394 def _save(self, outfile):
1395 """Save this config to an open stream object.
1396
1397 Parameters
1398 ----------
1399 outfile : file-like object
1400 Destination file object write the config into. Accepts strings not
1401 bytes.
1402 """
1403 for field in self._fields.values():
1404 field.save(outfile, self)
1405

◆ _setName()

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

Definition at line 248 of file configChoiceField.py.

248 def _setName(self, value):
249 if self._field.multi:
250 raise FieldValidationError(
251 self._field, self._config, "Multi-selection field has no attribute 'name'"
252 )
253 self._setSelection(value)
254

◆ _setNames()

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

Definition at line 227 of file configChoiceField.py.

227 def _setNames(self, value):
228 if not self._field.multi:
229 raise FieldValidationError(
230 self._field, self._config, "Single-selection field has no attribute 'names'"
231 )
232 self._setSelection(value)
233

◆ _setSelection()

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

Definition at line 203 of file configChoiceField.py.

203 def _setSelection(self, value, at=None, label="assignment"):
204 if self._config._frozen:
205 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config")
206
207 if at is None:
208 at = getCallStack(1)
209
210 if value is None:
211 self._selection = None
212 elif self._field.multi:
213 self._selection = SelectionSet(self, value, setHistory=False)
214 else:
215 if value not in self._dict:
216 self.__getitem__(value, at=at) # just invoke __getitem__ to make sure it's present
217 self._selection = value
218 self._history.append((value, at, label))
219

◆ _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 1618 of file config.py.

1618 def compare(self, other, shortcut=True, rtol=1e-8, atol=1e-8, output=None):
1619 """Compare this configuration to another `~lsst.pex.config.Config` for
1620 equality.
1621
1622 Parameters
1623 ----------
1624 other : `lsst.pex.config.Config`
1625 Other `~lsst.pex.config.Config` object to compare against this
1626 config.
1627 shortcut : `bool`, optional
1628 If `True`, return as soon as an inequality is found. Default is
1629 `True`.
1630 rtol : `float`, optional
1631 Relative tolerance for floating point comparisons.
1632 atol : `float`, optional
1633 Absolute tolerance for floating point comparisons.
1634 output : callable, optional
1635 A callable that takes a string, used (possibly repeatedly) to
1636 report inequalities.
1637
1638 Returns
1639 -------
1640 isEqual : `bool`
1641 `True` when the two `lsst.pex.config.Config` instances are equal.
1642 `False` if there is an inequality.
1643
1644 See Also
1645 --------
1646 lsst.pex.config.compareConfigs
1647
1648 Notes
1649 -----
1650 Unselected targets of `~lsst.pex.config.RegistryField` fields and
1651 unselected choices of `~lsst.pex.config.ConfigChoiceField` fields
1652 are not considered by this method.
1653
1654 Floating point comparisons are performed by `numpy.allclose`.
1655 """
1656 name1 = self._name if self._name is not None else "config"
1657 name2 = other._name if other._name is not None else "config"
1658 name = getComparisonName(name1, name2)
1659 return compareConfigs(name, self, other, shortcut=shortcut, rtol=rtol, atol=atol, output=output)
1660

◆ 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 1523 of file config.py.

1523 def formatHistory(self, name, **kwargs):
1524 """Format a configuration field's history to a human-readable format.
1525
1526 Parameters
1527 ----------
1528 name : `str`
1529 Name of a `~lsst.pex.config.Field` in this config.
1530 **kwargs
1531 Keyword arguments passed to `lsst.pex.config.history.format`.
1532
1533 Returns
1534 -------
1535 history : `str`
1536 A string containing the formatted history.
1537
1538 See Also
1539 --------
1540 lsst.pex.config.history.format
1541 """
1542 import lsst.pex.config.history as pexHist
1543
1544 return pexHist.format(self, name, **kwargs)
1545

◆ 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 580 of file configChoiceField.py.

580 def freeze(self, instance):
581 instanceDict = self.__get__(instance)
582 instanceDict.freeze()
583 for v in instanceDict.values():
584 v.freeze()
585

◆ 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 997 of file config.py.

997 def items(self):
998 """Get configurations as ``(field name, field value)`` pairs.
999
1000 Returns
1001 -------
1002 items : `~collections.abc.ItemsView`
1003 Iterator of tuples for each configuration. Tuple items are:
1004
1005 0. Field name.
1006 1. Field value.
1007 """
1008 return self._storage.items()
1009

◆ 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 977 of file config.py.

977 def keys(self):
978 """Get field names.
979
980 Returns
981 -------
982 names : `~collections.abc.KeysView`
983 List of `lsst.pex.config.Field` names.
984 """
985 return self._storage.keys()
986

◆ 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 1142 of file config.py.

1142 def load(self, filename, root="config"):
1143 """Modify this config in place by executing the Python code in a
1144 configuration file.
1145
1146 Parameters
1147 ----------
1148 filename : `str`
1149 Name of the configuration file. A configuration file is Python
1150 module.
1151 root : `str`, optional
1152 Name of the variable in file that refers to the config being
1153 overridden.
1154
1155 For example, the value of root is ``"config"`` and the file
1156 contains::
1157
1158 config.myField = 5
1159
1160 Then this config's field ``myField`` is set to ``5``.
1161
1162 See Also
1163 --------
1164 lsst.pex.config.Config.loadFromStream
1165 lsst.pex.config.Config.loadFromString
1166 lsst.pex.config.Config.save
1167 lsst.pex.config.Config.saveToStream
1168 lsst.pex.config.Config.saveToString
1169 """
1170 with open(filename) as f:
1171 code = compile(f.read(), filename=filename, mode="exec")
1172 self.loadFromString(code, root=root, filename=filename)
1173

◆ 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 1174 of file config.py.

1174 def loadFromStream(self, stream, root="config", filename=None, extraLocals=None):
1175 """Modify this Config in place by executing the Python code in the
1176 provided stream.
1177
1178 Parameters
1179 ----------
1180 stream : file-like object, `str`, `bytes`, or `~types.CodeType`
1181 Stream containing configuration override code. If this is a
1182 code object, it should be compiled with ``mode="exec"``.
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 filename : `str`, optional
1194 Name of the configuration file, or `None` if unknown or contained
1195 in the stream. Used for error reporting.
1196 extraLocals : `dict` of `str` to `object`, optional
1197 Any extra variables to include in local scope when loading.
1198
1199 Notes
1200 -----
1201 For backwards compatibility reasons, this method accepts strings, bytes
1202 and code objects as well as file-like objects. New code should use
1203 `loadFromString` instead for most of these types.
1204
1205 See Also
1206 --------
1207 lsst.pex.config.Config.load
1208 lsst.pex.config.Config.loadFromString
1209 lsst.pex.config.Config.save
1210 lsst.pex.config.Config.saveToStream
1211 lsst.pex.config.Config.saveToString
1212 """
1213 if hasattr(stream, "read"):
1214 if filename is None:
1215 filename = getattr(stream, "name", "?")
1216 code = compile(stream.read(), filename=filename, mode="exec")
1217 else:
1218 code = stream
1219 self.loadFromString(code, root=root, filename=filename, extraLocals=extraLocals)
1220

◆ 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 1221 of file config.py.

1221 def loadFromString(self, code, root="config", filename=None, extraLocals=None):
1222 """Modify this Config in place by executing the Python code in the
1223 provided string.
1224
1225 Parameters
1226 ----------
1227 code : `str`, `bytes`, or `~types.CodeType`
1228 Stream containing configuration override code.
1229 root : `str`, optional
1230 Name of the variable in file that refers to the config being
1231 overridden.
1232
1233 For example, the value of root is ``"config"`` and the file
1234 contains::
1235
1236 config.myField = 5
1237
1238 Then this config's field ``myField`` is set to ``5``.
1239 filename : `str`, optional
1240 Name of the configuration file, or `None` if unknown or contained
1241 in the stream. Used for error reporting.
1242 extraLocals : `dict` of `str` to `object`, optional
1243 Any extra variables to include in local scope when loading.
1244
1245 Raises
1246 ------
1247 ValueError
1248 Raised if a key in extraLocals is the same value as the value of
1249 the root argument.
1250
1251 See Also
1252 --------
1253 lsst.pex.config.Config.load
1254 lsst.pex.config.Config.loadFromStream
1255 lsst.pex.config.Config.save
1256 lsst.pex.config.Config.saveToStream
1257 lsst.pex.config.Config.saveToString
1258 """
1259 if filename is None:
1260 # try to determine the file name; a compiled string
1261 # has attribute "co_filename",
1262 filename = getattr(code, "co_filename", "?")
1263 with RecordingImporter() as importer:
1264 globals = {"__file__": filename}
1265 local = {root: self}
1266 if extraLocals is not None:
1267 # verify the value of root was not passed as extra local args
1268 if root in extraLocals:
1269 raise ValueError(
1270 f"{root} is reserved and cannot be used as a variable name in extraLocals"
1271 )
1272 local.update(extraLocals)
1273 exec(code, globals, local)
1274
1275 self._imports.update(importer.getModules())
1276

◆ 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 547 of file configChoiceField.py.

547 def rename(self, instance):
548 instanceDict = self.__get__(instance)
549 fullname = _joinNamePath(instance._name, self.name)
550 instanceDict._rename(fullname)
551

◆ 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 592 of file configChoiceField.py.

592 def save(self, outfile, instance):
593 instanceDict = self.__get__(instance)
594 fullname = _joinNamePath(instance._name, self.name)
595 for v in instanceDict.values():
596 v._save(outfile)
597 if self.multi:
598 outfile.write(f"{fullname}.names={sorted(instanceDict.names)!r}\n")
599 else:
600 outfile.write(f"{fullname}.name={instanceDict.name!r}\n")
601

◆ 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 1339 of file config.py.

1339 def saveToStream(self, outfile, root="config", skipImports=False):
1340 """Save a configuration file to a stream, which, when loaded,
1341 reproduces this config.
1342
1343 Parameters
1344 ----------
1345 outfile : file-like object
1346 Destination file object write the config into. Accepts strings not
1347 bytes.
1348 root : `str`, optional
1349 Name to use for the root config variable. The same value must be
1350 used when loading (see `lsst.pex.config.Config.load`).
1351 skipImports : `bool`, optional
1352 If `True` then do not include ``import`` statements in output,
1353 this is to support human-oriented output from ``pipetask`` where
1354 additional clutter is not useful.
1355
1356 See Also
1357 --------
1358 lsst.pex.config.Config.save
1359 lsst.pex.config.Config.saveToString
1360 lsst.pex.config.Config.load
1361 lsst.pex.config.Config.loadFromStream
1362 lsst.pex.config.Config.loadFromString
1363 """
1364 tmp = self._name
1365 self._rename(root)
1366 try:
1367 if not skipImports:
1368 self._collectImports()
1369 # Remove self from the set, as it is handled explicitly below
1370 self._imports.remove(self.__module__)
1371 configType = type(self)
1372 typeString = _typeStr(configType)
1373 outfile.write(f"import {configType.__module__}\n")
1374 # We are required to write this on a single line because
1375 # of later regex matching, rather than adopting black style
1376 # formatting.
1377 outfile.write(
1378 f'assert type({root}) is {typeString}, f"config is of type '
1379 f'{{type({root}).__module__}}.{{type({root}).__name__}} instead of {typeString}"\n\n'
1380 )
1381 for imp in sorted(self._imports):
1382 if imp in sys.modules and sys.modules[imp] is not None:
1383 outfile.write(f"import {imp}\n")
1384 self._save(outfile)
1385 finally:
1386 self._rename(tmp)
1387

◆ 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 1311 of file config.py.

1311 def saveToString(self, skipImports=False):
1312 """Return the Python script form of this configuration as an executable
1313 string.
1314
1315 Parameters
1316 ----------
1317 skipImports : `bool`, optional
1318 If `True` then do not include ``import`` statements in output,
1319 this is to support human-oriented output from ``pipetask`` where
1320 additional clutter is not useful.
1321
1322 Returns
1323 -------
1324 code : `str`
1325 A code string readable by `loadFromString`.
1326
1327 See Also
1328 --------
1329 lsst.pex.config.Config.save
1330 lsst.pex.config.Config.saveToStream
1331 lsst.pex.config.Config.load
1332 lsst.pex.config.Config.loadFromStream
1333 lsst.pex.config.Config.loadFromString
1334 """
1335 buffer = io.StringIO()
1336 self.saveToStream(buffer, skipImports=skipImports)
1337 return buffer.getvalue()
1338

◆ 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.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.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 1071 of file config.py.

1071 def setDefaults(self):
1072 """Subclass hook for computing defaults.
1073
1074 Notes
1075 -----
1076 Derived `~lsst.pex.config.Config` classes that must compute defaults
1077 rather than using the `~lsst.pex.config.Field` instances's defaults
1078 should do so here. To correctly use inherited defaults,
1079 implementations of ``setDefaults`` must call their base class's
1080 ``setDefaults``.
1081 """
1082 pass
1083

◆ 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 564 of file configChoiceField.py.

564 def toDict(self, instance):
565 instanceDict = self.__get__(instance)
566
567 dict_ = {}
568 if self.multi:
569 dict_["names"] = instanceDict.names
570 else:
571 dict_["name"] = instanceDict.name
572
573 values = {}
574 for k, v in instanceDict.items():
575 values[k] = v.toDict()
576 dict_["values"] = values
577
578 return dict_
579

◆ types()

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

Definition at line 191 of file configChoiceField.py.

191 def types(self):
192 return self._typemap if self._typemap is not None else self._field.typemap
193

◆ 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 1084 of file config.py.

1084 def update(self, **kw):
1085 """Update values of fields specified by the keyword arguments.
1086
1087 Parameters
1088 ----------
1089 **kw
1090 Keywords are configuration field names. Values are configuration
1091 field values.
1092
1093 Notes
1094 -----
1095 The ``__at`` and ``__label`` keyword arguments are special internal
1096 keywords. They are used to strip out any internal steps from the
1097 history tracebacks of the config. Do not modify these keywords to
1098 subvert a `~lsst.pex.config.Config` instance's history.
1099
1100 Examples
1101 --------
1102 This is a config with three fields:
1103
1104 >>> from lsst.pex.config import Config, Field
1105 >>> class DemoConfig(Config):
1106 ... fieldA = Field(doc="Field A", dtype=int, default=42)
1107 ... fieldB = Field(doc="Field B", dtype=bool, default=True)
1108 ... fieldC = Field(doc="Field C", dtype=str, default="Hello world")
1109 >>> config = DemoConfig()
1110
1111 These are the default values of each field:
1112
1113 >>> for name, value in config.iteritems():
1114 ... print(f"{name}: {value}")
1115 fieldA: 42
1116 fieldB: True
1117 fieldC: 'Hello world'
1118
1119 Using this method to update ``fieldA`` and ``fieldC``:
1120
1121 >>> config.update(fieldA=13, fieldC="Updated!")
1122
1123 Now the values of each field are:
1124
1125 >>> for name, value in config.iteritems():
1126 ... print(f"{name}: {value}")
1127 fieldA: 13
1128 fieldB: True
1129 fieldC: 'Updated!'
1130 """
1131 at = kw.pop("__at", getCallStack())
1132 label = kw.pop("__label", "update")
1133
1134 for name, value in kw.items():
1135 try:
1136 field = self._fields[name]
1137 field.__set__(self, value, at=at, label=label)
1138 except KeyError as e:
1139 e.add_note(f"No field of name {name} exists in config type {_typeStr(self)}")
1140 raise
1141

◆ 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 552 of file configChoiceField.py.

552 def validate(self, instance):
553 instanceDict = self.__get__(instance)
554 if instanceDict.active is None and not self.optional:
555 msg = "Required field cannot be None"
556 raise FieldValidationError(self, instance, msg)
557 elif instanceDict.active is not None:
558 if self.multi:
559 for a in instanceDict.active:
560 a.validate()
561 else:
562 instanceDict.active.validate()
563

◆ values()

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

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

Definition at line 987 of file config.py.

987 def values(self):
988 """Get field values.
989
990 Returns
991 -------
992 values : `~collections.abc.ValuesView`
993 Iterator of field values.
994 """
995 return self._storage.values()
996

Member Data Documentation

◆ _config

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

Definition at line 184 of file configChoiceField.py.

◆ _dict

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

Definition at line 182 of file configChoiceField.py.

◆ _field

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

Definition at line 185 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 1390 of file config.py.

◆ _history

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

Definition at line 970 of file config.py.

◆ _imports

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

Definition at line 971 of file config.py.

◆ _name

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

Definition at line 1493 of file config.py.

◆ _selection

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

Definition at line 183 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 968 of file config.py.

◆ _typemap

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

Definition at line 188 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 484 of file configChoiceField.py.

◆ multi

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

Definition at line 498 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 497 of file configChoiceField.py.

◆ types

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

Definition at line 198 of file configChoiceField.py.

Property Documentation

◆ active

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

Definition at line 283 of file configChoiceField.py.

◆ history

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

Definition at line 1546 of file config.py.

◆ name

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

Definition at line 268 of file configChoiceField.py.

◆ names

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

Definition at line 262 of file configChoiceField.py.


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