Config

class lsst.pex.config.Config

Bases: object

Base class for configuration (config) objects.

Notes

A Config object will usually have several 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, items, iteritems, iterkeys, and itervalues. 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 Field instances (or instances of 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']

Attributes Summary

history Read-only history.

Methods Summary

compare(other[, shortcut, rtol, atol, output]) Compare this configuration to another Config for equality.
formatHistory(name, **kwargs) Format a configuration field’s history to a human-readable format.
freeze() Make this config, and all subconfigs, read-only.
items() Get configurations as (field name, field value) pairs.
iteritems() Iterate over (field name, field value) pairs.
iterkeys() Iterate over field names
itervalues() Iterate over field values.
keys() Get field names.
load(filename[, root]) Modify this config in place by executing the Python code in a configuration file.
loadFromStream(stream[, root, filename]) Modify this Config in place by executing the Python code in the provided stream.
names() Get all the field names in the config, recursively.
save(filename[, root]) Save a Python script to the named file, which, when loaded, reproduces this config.
saveToStream(outfile[, root, skipImports]) Save a configuration file to a stream, which, when loaded, reproduces this config.
setDefaults() Subclass hook for computing defaults.
toDict() Make a dictionary of field names and their values.
update(**kw) Update values of fields specified by the keyword arguments.
validate() Validate the Config, raising an exception if invalid.
values() Get field values.

Attributes Documentation

history

Read-only history.

Methods Documentation

compare(other, shortcut=True, rtol=1e-08, atol=1e-08, output=None)

Compare this configuration to another Config for equality.

Parameters:
other : lsst.pex.config.Config

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

Notes

Unselected targets of RegistryField fields and unselected choices of ConfigChoiceField fields are not considered by this method.

Floating point comparisons are performed by numpy.allclose.

formatHistory(name, **kwargs)

Format a configuration field’s history to a human-readable format.

Parameters:
name : str

Name of a Field in this config.

kwargs

Keyword arguments passed to lsst.pex.config.history.format.

Returns:
history : str

A string containing the formatted history.

freeze()

Make this config, and all subconfigs, read-only.

items()

Get configurations as (field name, field value) pairs.

Returns:
items : list

List of tuples for each configuration. Tuple items are:

  1. Field name.
  2. Field value.
iteritems()

Iterate over (field name, field value) pairs.

Yields:
item : tuple

Tuple items are:

  1. Field name.
  2. Field value.
iterkeys()

Iterate over field names

Yields:
key : str

A field’s key (attribute name).

itervalues()

Iterate over field values.

Yields:
value : obj

A field value.

keys()

Get field names.

Returns:
names : list

List of lsst.pex.config.Field names.

load(filename, root='config')

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.

Deprecated: For backwards compatibility, older config files that use root="root" instead of root="config" will be loaded with a warning printed to sys.stderr. This feature will be removed at some point.

See also

lsst.pex.config.Config.loadFromStream, lsst.pex.config.Config.save, lsst.pex.config.Config.saveFromStream

loadFromStream(stream, root='config', filename=None)

Modify this Config in place by executing the Python code in the provided stream.

Parameters:
stream : file-like object, str, or compiled string

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.

Deprecated: For backwards compatibility, older config files that use root="root" instead of root="config" will be loaded with a warning printed to sys.stderr. This feature will be removed at some point.

filename : str, optional

Name of the configuration file, or None if unknown or contained in the stream. Used for error reporting.

See also

lsst.pex.config.Config.load, lsst.pex.config.Config.save, lsst.pex.config.Config.saveFromStream

names()

Get all the field names in the config, recursively.

Returns:
names : list of str

Field names.

save(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).

saveToStream(outfile, root='config', skipImports=False)

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

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.

setDefaults()

Subclass hook for computing defaults.

Notes

Derived Config classes that must compute defaults rather than using the Field instances’s defaults should do so here. To correctly use inherited defaults, implementations of setDefaults must call their base class’s setDefaults.

toDict()

Make a dictionary of field names and their values.

Returns:
dict_ : dict

Dictionary with keys that are Field names. Values are Field values.

Notes

This method uses the toDict method of individual fields. Subclasses of Field may need to implement a toDict method for this method to work.

update(**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 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()

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 validate methods.

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

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

values()

Get field values.

Returns:
values : list

List of field values.