lsst.pex.config ge80df9fc40+0778f1db16
 
Loading...
Searching...
No Matches
lsst.pex.config.config.Config Class Reference
Inheritance diagram for lsst.pex.config.config.Config:
lsst.pex.config.config.ConfigMeta lsst.pex.config.configChoiceField.ConfigInstanceDict lsst.pex.config.configDictField.ConfigDict lsst.pex.config.configurableActions._configurableAction.ConfigurableAction lsst.pex.config.configurableActions.tests.TestConfig lsst.pex.config.configChoiceField.ConfigChoiceField lsst.pex.config.registry.RegistryInstanceDict lsst.pex.config.configurableActions.tests.ActionTest1 lsst.pex.config.configurableActions.tests.ActionTest2 lsst.pex.config.configurableActions.tests.ActionTest3 lsst.pex.config.configurableActions.tests.TestDivideAction lsst.pex.config.configurableActions.tests.TestSingleColumnAction lsst.pex.config.registry.RegistryField

Public Member Functions

 __iter__ (self)
 
 keys (self)
 
 values (self)
 
 items (self)
 
 __contains__ (self, name)
 
 __new__ (cls, *args, **kw)
 
Config copy (self)
 
 __reduce__ (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)
 
 save (self, filename, root="config")
 
 saveToString (self, skipImports=False)
 
 saveToStream (self, outfile, root="config", skipImports=False)
 
 freeze (self)
 
 toDict (self)
 
 names (self)
 
 validate (self)
 
 formatHistory (self, name, **kwargs)
 
 __setattr__ (self, attr, value, at=None, label="assignment")
 
 __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 Member Functions inherited from lsst.pex.config.config.ConfigMeta
 __init__ (cls, name, bases, dict_)
 
 __setattr__ (cls, name, value)
 

Protected Member Functions

tuple[ResourcePath|None, str] _filename_to_resource (self, ResourcePathExpression|None filename=None)
 
 _loadFromString (self, code, root="config", filename=None, extraLocals=None)
 
 _save (self, outfile)
 
 _collectImports (self)
 
 _rename (self, name)
 
 _fromPython (cls, config_py)
 

Protected Attributes

bool _frozen = True
 
 _name = name
 
- Protected Attributes inherited from lsst.pex.config.config.ConfigMeta
dict _fields = {}
 
 _source = getStackFrame()
 

Static Protected Attributes

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

Properties

 history = property(lambda x: x._history)
 

Detailed Description

Base class for configuration (*config*) objects.

Notes
-----
A ``Config`` object will usually have several `~lsst.pex.config.Field`
instances as class attributes. These are used to define most of the base
class behavior.

``Config`` implements a mapping API that provides many `dict`-like methods,
such as `keys`, `values`, and `items`. ``Config`` instances also support
the ``in`` operator to test if a field is in the config. Unlike a `dict`,
``Config`` classes are not subscriptable. Instead, access individual
fields as attributes of the configuration instance.

Examples
--------
Config classes are subclasses of ``Config`` that have
`~lsst.pex.config.Field` instances (or instances of
`~lsst.pex.config.Field` subclasses) as class attributes:

>>> from lsst.pex.config import Config, Field, ListField
>>> class DemoConfig(Config):
...     intField = Field(doc="An integer field", dtype=int, default=42)
...     listField = ListField(
...         doc="List of favorite beverages.",
...         dtype=str,
...         default=["coffee", "green tea", "water"],
...     )
>>> config = DemoConfig()

Configs support many `dict`-like APIs:

>>> config.keys()
['intField', 'listField']
>>> "intField" in config
True

Individual fields can be accessed as attributes of the configuration:

>>> config.intField
42
>>> config.listField.append("earl grey tea")
>>> print(config.listField)
['coffee', 'green tea', 'water', 'earl grey tea']

Member Function Documentation

◆ __contains__()

lsst.pex.config.config.Config.__contains__ ( self,
name )
Return `True` if the specified field exists in this config.

Parameters
----------
name : `str`
    Field name to test for.

Returns
-------
in : `bool`
    `True` if the specified field exists in the config.

◆ __init_subclass__()

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

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

◆ __iter__()

lsst.pex.config.config.Config.__iter__ ( self)
Iterate over fields.

◆ __new__()

lsst.pex.config.config.Config.__new__ ( cls,
* args,
** kw )
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.

◆ __reduce__()

lsst.pex.config.config.Config.__reduce__ ( self)
Reduction for pickling (function with arguments to reproduce).

We need to condense and reconstitute the `~lsst.pex.config.Config`,
since it may contain lambdas (as the ``check`` elements) that cannot
be pickled.

◆ __setattr__()

lsst.pex.config.config.Config.__setattr__ ( self,
attr,
value,
at = None,
label = "assignment" )
Set an attribute (such as a field's value).

Notes
-----
Unlike normal Python objects, `~lsst.pex.config.Config` objects are
locked such that no additional attributes nor properties may be added
to them dynamically.

Although this is not the standard Python behavior, it helps to protect
users from accidentally mispelling a field name, or trying to set a
non-existent field.

◆ _collectImports()

lsst.pex.config.config.Config._collectImports ( self)
protected
Add module containing self to the list of things to import and
then loops over all the fields in the config calling a corresponding
collect method.

The field method will call _collectImports on any
configs it may own and return the set of things to import. This
returned set will be merged with the set of imports for this config
class.

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField.

◆ _filename_to_resource()

tuple[ResourcePath | None, str] lsst.pex.config.config.Config._filename_to_resource ( self,
ResourcePathExpression | None filename = None )
protected
Create resource path from filename.

Parameters
----------
filename : `lsst.resources.ResourcePathExpression` or `None`
    The URI expression associated with this config. Can be `None`
    if no file URI is known.

Returns
-------
resource : `lsst.resources.ResourcePath` or `None`
    The resource version of the filename. Returns `None` if no filename
    was given or refers to unspecified value.
file_string : `str`
    String form of the resource for use in ``__file__``

◆ _fromPython()

lsst.pex.config.config.Config._fromPython ( cls,
config_py )
protected
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.

◆ _loadFromString()

lsst.pex.config.config.Config._loadFromString ( self,
code,
root = "config",
filename = None,
extraLocals = None )
protected
Update config from string.

Assumes relative directory path context has been setup by caller.

◆ _rename()

lsst.pex.config.config.Config._rename ( self,
name )
protected
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 in lsst.pex.config.configChoiceField.ConfigInstanceDict.

◆ _save()

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

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

◆ compare()

lsst.pex.config.config.Config.compare ( self,
other,
shortcut = True,
rtol = 1e-8,
atol = 1e-8,
output = None )
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 : `collections.abc.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`.

◆ copy()

Config lsst.pex.config.config.Config.copy ( self)
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.

◆ formatHistory()

lsst.pex.config.config.Config.formatHistory ( self,
name,
** kwargs )
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

◆ freeze()

lsst.pex.config.config.Config.freeze ( self)
Make this config, and all subconfigs, read-only.

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField, and lsst.pex.config.configChoiceField.ConfigInstanceDict.

◆ items()

lsst.pex.config.config.Config.items ( self)
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.

◆ keys()

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

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

◆ load()

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

Parameters
----------
filename : `lsst.resources.ResourcePathExpression`
    Name of the configuration URI. A configuration file is a Python
    module. Since configuration files are Python code, remote URIs
    are not allowed.
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

◆ loadFromStream()

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

Parameters
----------
stream : `typing.IO`, `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 and to set ``__file__``
    variable in config.
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

◆ loadFromString()

lsst.pex.config.config.Config.loadFromString ( self,
code,
root = "config",
filename = None,
extraLocals = None )
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 : `lsst.resources.ResourcePathExpression`, optional
    URI of the configuration file, or `None` if unknown or contained
    in the stream. Used for error reporting and to set ``__file__``
    variable. Required to be set if the string config attempts to
    load other configs using either relative path or ``__file__``.
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

◆ names()

lsst.pex.config.config.Config.names ( self)
Get all the field names in the config, recursively.

Returns
-------
names : `list` of `str`
    Field names.

◆ save()

lsst.pex.config.config.Config.save ( self,
filename,
root = "config" )
Save a Python script to the named file, which, when loaded,
reproduces this config.

Parameters
----------
filename : `str`
    Desination filename of this configuration.
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`).

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

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField.

◆ saveToStream()

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

Parameters
----------
outfile : `typing.TextIO`
    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

◆ saveToString()

lsst.pex.config.config.Config.saveToString ( self,
skipImports = False )
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

◆ setDefaults()

lsst.pex.config.config.Config.setDefaults ( self)
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``.

◆ toDict()

lsst.pex.config.config.Config.toDict ( self)
Make a dictionary of field names and their values.

Returns
-------
dict_ : `dict`
    Dictionary with keys that are `~lsst.pex.config.Field` names.
    Values are `~lsst.pex.config.Field` values.

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

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

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField.

◆ update()

lsst.pex.config.config.Config.update ( self,
** kw )
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!'

◆ validate()

lsst.pex.config.config.Config.validate ( self)
Validate the Config, raising an exception if invalid.

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

Notes
-----
The base class implementation performs type checks on all fields by
calling their `~lsst.pex.config.Field.validate` methods.

Complex single-field validation can be defined by deriving new Field
types. For convenience, some derived `lsst.pex.config.Field`-types
(`~lsst.pex.config.ConfigField` and
`~lsst.pex.config.ConfigChoiceField`) are defined in
``lsst.pex.config`` that handle recursing into subconfigs.

Inter-field relationships should only be checked in derived
`~lsst.pex.config.Config` classes after calling this method, and base
validation is complete.

Reimplemented in lsst.pex.config.configChoiceField.ConfigChoiceField, lsst.pex.config.configurableActions.tests.ActionTest1, lsst.pex.config.configurableActions.tests.ActionTest2, lsst.pex.config.configurableActions.tests.ActionTest3, and lsst.pex.config.configurableActions.tests.TestDivideAction.

◆ values()

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

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

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