LSSTApplications  18.0.0+106,18.0.0+50,19.0.0,19.0.0+1,19.0.0+10,19.0.0+11,19.0.0+13,19.0.0+17,19.0.0+2,19.0.0-1-g20d9b18+6,19.0.0-1-g425ff20,19.0.0-1-g5549ca4,19.0.0-1-g580fafe+6,19.0.0-1-g6fe20d0+1,19.0.0-1-g7011481+9,19.0.0-1-g8c57eb9+6,19.0.0-1-gb5175dc+11,19.0.0-1-gdc0e4a7+9,19.0.0-1-ge272bc4+6,19.0.0-1-ge3aa853,19.0.0-10-g448f008b,19.0.0-12-g6990b2c,19.0.0-2-g0d9f9cd+11,19.0.0-2-g3d9e4fb2+11,19.0.0-2-g5037de4,19.0.0-2-gb96a1c4+3,19.0.0-2-gd955cfd+15,19.0.0-3-g2d13df8,19.0.0-3-g6f3c7dc,19.0.0-4-g725f80e+11,19.0.0-4-ga671dab3b+1,19.0.0-4-gad373c5+3,19.0.0-5-ga2acb9c+2,19.0.0-5-gfe96e6c+2,w.2020.01
LSSTDataManagementBasePackage
Public Member Functions | Properties | List of all members
pex.config.config.Config Class Reference
Inheritance diagram for pex.config.config.Config:
pex.config.config.ConfigMeta

Public Member Functions

def __iter__ (self)
 
def keys (self)
 
def values (self)
 
def items (self)
 
def iteritems (self)
 
def itervalues (self)
 
def iterkeys (self)
 
def __contains__ (self, name)
 Return True if the specified field exists in this config. More...
 
def __new__ (cls, args, kw)
 
def __reduce__ (self)
 
def setDefaults (self)
 
def update (self, kw)
 
def load (self, filename, root="config")
 
def loadFromStream (self, stream, root="config", filename=None)
 
def save (self, filename, root="config")
 
def saveToStream (self, outfile, root="config")
 
def freeze (self)
 
def toDict (self)
 
def names (self)
 
def validate (self)
 
def formatHistory (self, name, kwargs)
 
def __setattr__ (self, attr, value, at=None, label="assignment")
 
def __delattr__ (self, attr, at=None, label="deletion")
 
def __eq__ (self, other)
 
def __ne__ (self, other)
 
def __str__ (self)
 
def __repr__ (self)
 
def compare (self, other, shortcut=True, rtol=1E-8, atol=1E-8, output=None)
 
def __setattr__ (cls, name, value)
 

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`, `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
`~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']

Definition at line 684 of file config.py.

Member Function Documentation

◆ __contains__()

def pex.config.config.Config.__contains__ (   self,
  name 
)

Return True if the specified field exists in this config.

Parameters
[in]namefield name to test for

Definition at line 825 of file config.py.

825  def __contains__(self, name):
826  """!Return True if the specified field exists in this config
827 
828  @param[in] name field name to test for
829  """
830  return self._storage.__contains__(name)
831 

◆ __delattr__()

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

Definition at line 1304 of file config.py.

1304  def __delattr__(self, attr, at=None, label="deletion"):
1305  if attr in self._fields:
1306  if at is None:
1307  at = getCallStack()
1308  self._fields[attr].__delete__(self, at=at, label=label)
1309  else:
1310  object.__delattr__(self, attr)
1311 
def getCallStack(skip=0)
Definition: callStack.py:175

◆ __eq__()

def pex.config.config.Config.__eq__ (   self,
  other 
)

Definition at line 1312 of file config.py.

1312  def __eq__(self, other):
1313  if type(other) == type(self):
1314  for name in self._fields:
1315  thisValue = getattr(self, name)
1316  otherValue = getattr(other, name)
1317  if isinstance(thisValue, float) and math.isnan(thisValue):
1318  if not math.isnan(otherValue):
1319  return False
1320  elif thisValue != otherValue:
1321  return False
1322  return True
1323  return False
1324 
table::Key< int > type
Definition: Detector.cc:163

◆ __iter__()

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

Definition at line 730 of file config.py.

730  def __iter__(self):
731  """Iterate over fields.
732  """
733  return self._fields.__iter__()
734 

◆ __ne__()

def pex.config.config.Config.__ne__ (   self,
  other 
)

Definition at line 1325 of file config.py.

1325  def __ne__(self, other):
1326  return not self.__eq__(other)
1327 

◆ __new__()

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

Definition at line 832 of file config.py.

832  def __new__(cls, *args, **kw):
833  """Allocate a new `lsst.pex.config.Config` object.
834 
835  In order to ensure that all Config object are always in a proper state
836  when handed to users or to derived `~lsst.pex.config.Config` classes,
837  some attributes are handled at allocation time rather than at
838  initialization.
839 
840  This ensures that even if a derived `~lsst.pex.config.Config` class
841  implements ``__init__``, its author does not need to be concerned about
842  when or even the base ``Config.__init__`` should be called.
843  """
844  name = kw.pop("__name", None)
845  at = kw.pop("__at", getCallStack())
846  # remove __label and ignore it
847  kw.pop("__label", "default")
848 
849  instance = object.__new__(cls)
850  instance._frozen = False
851  instance._name = name
852  instance._storage = {}
853  instance._history = {}
854  instance._imports = set()
855  # load up defaults
856  for field in instance._fields.values():
857  instance._history[field.name] = []
858  field.__set__(instance, field.default, at=at + [field.source], label="default")
859  # set custom default-overides
860  instance.setDefaults()
861  # set constructor overides
862  instance.update(__at=at, **kw)
863  return instance
864 
def getCallStack(skip=0)
Definition: callStack.py:175
daf::base::PropertySet * set
Definition: fits.cc:902

◆ __reduce__()

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

Definition at line 865 of file config.py.

865  def __reduce__(self):
866  """Reduction for pickling (function with arguments to reproduce).
867 
868  We need to condense and reconstitute the `~lsst.pex.config.Config`,
869  since it may contain lambdas (as the ``check`` elements) that cannot
870  be pickled.
871  """
872  # The stream must be in characters to match the API but pickle
873  # requires bytes
874  stream = io.StringIO()
875  self.saveToStream(stream)
876  return (unreduceConfig, (self.__class__, stream.getvalue().encode()))
877 

◆ __repr__()

def pex.config.config.Config.__repr__ (   self)

Definition at line 1331 of file config.py.

1331  def __repr__(self):
1332  return "%s(%s)" % (
1333  _typeStr(self),
1334  ", ".join("%s=%r" % (k, v) for k, v in self.toDict().items() if v is not None)
1335  )
1336 
std::vector< SchemaItem< Flag > > * items

◆ __setattr__() [1/2]

def pex.config.config.ConfigMeta.__setattr__ (   cls,
  name,
  value 
)
inherited

Definition at line 137 of file config.py.

137  def __setattr__(cls, name, value):
138  if isinstance(value, Field):
139  value.name = name
140  cls._fields[name] = value
141  type.__setattr__(cls, name, value)
142 
143 

◆ __setattr__() [2/2]

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

Definition at line 1272 of file config.py.

1272  def __setattr__(self, attr, value, at=None, label="assignment"):
1273  """Set an attribute (such as a field's value).
1274 
1275  Notes
1276  -----
1277  Unlike normal Python objects, `~lsst.pex.config.Config` objects are
1278  locked such that no additional attributes nor properties may be added
1279  to them dynamically.
1280 
1281  Although this is not the standard Python behavior, it helps to protect
1282  users from accidentally mispelling a field name, or trying to set a
1283  non-existent field.
1284  """
1285  if attr in self._fields:
1286  if self._fields[attr].deprecated is not None:
1287  fullname = _joinNamePath(self._name, self._fields[attr].name)
1288  warnings.warn(f"Config field {fullname} is deprecated: {self._fields[attr].deprecated}",
1289  FutureWarning, stacklevel=2)
1290  if at is None:
1291  at = getCallStack()
1292  # This allows Field descriptors to work.
1293  self._fields[attr].__set__(self, value, at=at, label=label)
1294  elif hasattr(getattr(self.__class__, attr, None), '__set__'):
1295  # This allows properties and other non-Field descriptors to work.
1296  return object.__setattr__(self, attr, value)
1297  elif attr in self.__dict__ or attr in ("_name", "_history", "_storage", "_frozen", "_imports"):
1298  # This allows specific private attributes to work.
1299  self.__dict__[attr] = value
1300  else:
1301  # We throw everything else.
1302  raise AttributeError("%s has no attribute %s" % (_typeStr(self), attr))
1303 
def getCallStack(skip=0)
Definition: callStack.py:175

◆ __str__()

def pex.config.config.Config.__str__ (   self)

Definition at line 1328 of file config.py.

1328  def __str__(self):
1329  return str(self.toDict())
1330 

◆ compare()

def 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 : 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 1337 of file config.py.

1337  def compare(self, other, shortcut=True, rtol=1E-8, atol=1E-8, output=None):
1338  """Compare this configuration to another `~lsst.pex.config.Config` for
1339  equality.
1340 
1341  Parameters
1342  ----------
1343  other : `lsst.pex.config.Config`
1344  Other `~lsst.pex.config.Config` object to compare against this
1345  config.
1346  shortcut : `bool`, optional
1347  If `True`, return as soon as an inequality is found. Default is
1348  `True`.
1349  rtol : `float`, optional
1350  Relative tolerance for floating point comparisons.
1351  atol : `float`, optional
1352  Absolute tolerance for floating point comparisons.
1353  output : callable, optional
1354  A callable that takes a string, used (possibly repeatedly) to
1355  report inequalities.
1356 
1357  Returns
1358  -------
1359  isEqual : `bool`
1360  `True` when the two `lsst.pex.config.Config` instances are equal.
1361  `False` if there is an inequality.
1362 
1363  See also
1364  --------
1365  lsst.pex.config.compareConfigs
1366 
1367  Notes
1368  -----
1369  Unselected targets of `~lsst.pex.config.RegistryField` fields and
1370  unselected choices of `~lsst.pex.config.ConfigChoiceField` fields
1371  are not considered by this method.
1372 
1373  Floating point comparisons are performed by `numpy.allclose`.
1374  """
1375  name1 = self._name if self._name is not None else "config"
1376  name2 = other._name if other._name is not None else "config"
1377  name = getComparisonName(name1, name2)
1378  return compareConfigs(name, self, other, shortcut=shortcut,
1379  rtol=rtol, atol=atol, output=output)
1380 
1381 
def compareConfigs(name, c1, c2, shortcut=True, rtol=1E-8, atol=1E-8, output=None)
Definition: comparison.py:111
def getComparisonName(name1, name2)
Definition: comparison.py:40

◆ formatHistory()

def 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

Definition at line 1246 of file config.py.

1246  def formatHistory(self, name, **kwargs):
1247  """Format a configuration field's history to a human-readable format.
1248 
1249  Parameters
1250  ----------
1251  name : `str`
1252  Name of a `~lsst.pex.config.Field` in this config.
1253  kwargs
1254  Keyword arguments passed to `lsst.pex.config.history.format`.
1255 
1256  Returns
1257  -------
1258  history : `str`
1259  A string containing the formatted history.
1260 
1261  See also
1262  --------
1263  lsst.pex.config.history.format
1264  """
1265  import lsst.pex.config.history as pexHist
1266  return pexHist.format(self, name, **kwargs)
1267 

◆ freeze()

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

Definition at line 1112 of file config.py.

1112  def freeze(self):
1113  """Make this config, and all subconfigs, read-only.
1114  """
1115  self._frozen = True
1116  for field in self._fields.values():
1117  field.freeze(self)
1118 

◆ items()

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

Returns
-------
items : `list`
    List of tuples for each configuration. Tuple items are:

    0. Field name.
    1. Field value.

See also
--------
lsst.pex.config.Config.iteritems

Definition at line 763 of file config.py.

763  def items(self):
764  """Get configurations as ``(field name, field value)`` pairs.
765 
766  Returns
767  -------
768  items : `list`
769  List of tuples for each configuration. Tuple items are:
770 
771  0. Field name.
772  1. Field value.
773 
774  See also
775  --------
776  lsst.pex.config.Config.iteritems
777  """
778  return list(self._storage.items())
779 
std::vector< SchemaItem< Flag > > * items
daf::base::PropertyList * list
Definition: fits.cc:903

◆ iteritems()

def pex.config.config.Config.iteritems (   self)
Iterate over (field name, field value) pairs.

Yields
------
item : `tuple`
    Tuple items are:

    0. Field name.
    1. Field value.

See also
--------
lsst.pex.config.Config.items

Definition at line 780 of file config.py.

780  def iteritems(self):
781  """Iterate over (field name, field value) pairs.
782 
783  Yields
784  ------
785  item : `tuple`
786  Tuple items are:
787 
788  0. Field name.
789  1. Field value.
790 
791  See also
792  --------
793  lsst.pex.config.Config.items
794  """
795  return iter(self._storage.items())
796 
std::vector< SchemaItem< Flag > > * items

◆ iterkeys()

def pex.config.config.Config.iterkeys (   self)
Iterate over field names

Yields
------
key : `str`
    A field's key (attribute name).

See also
--------
lsst.pex.config.Config.values

Definition at line 811 of file config.py.

811  def iterkeys(self):
812  """Iterate over field names
813 
814  Yields
815  ------
816  key : `str`
817  A field's key (attribute name).
818 
819  See also
820  --------
821  lsst.pex.config.Config.values
822  """
823  return iter(self.storage.keys())
824 

◆ itervalues()

def pex.config.config.Config.itervalues (   self)
Iterate over field values.

Yields
------
value : obj
    A field value.

See also
--------
lsst.pex.config.Config.values

Definition at line 797 of file config.py.

797  def itervalues(self):
798  """Iterate over field values.
799 
800  Yields
801  ------
802  value : obj
803  A field value.
804 
805  See also
806  --------
807  lsst.pex.config.Config.values
808  """
809  return iter(self.storage.values())
810 

◆ keys()

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

Returns
-------
names : `list`
    List of `lsst.pex.config.Field` names.

See also
--------
lsst.pex.config.Config.iterkeys

Definition at line 735 of file config.py.

735  def keys(self):
736  """Get field names.
737 
738  Returns
739  -------
740  names : `list`
741  List of `lsst.pex.config.Field` names.
742 
743  See also
744  --------
745  lsst.pex.config.Config.iterkeys
746  """
747  return list(self._storage.keys())
748 
daf::base::PropertyList * list
Definition: fits.cc:903

◆ load()

def 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 : `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

Definition at line 951 of file config.py.

951  def load(self, filename, root="config"):
952  """Modify this config in place by executing the Python code in a
953  configuration file.
954 
955  Parameters
956  ----------
957  filename : `str`
958  Name of the configuration file. A configuration file is Python
959  module.
960  root : `str`, optional
961  Name of the variable in file that refers to the config being
962  overridden.
963 
964  For example, the value of root is ``"config"`` and the file
965  contains::
966 
967  config.myField = 5
968 
969  Then this config's field ``myField`` is set to ``5``.
970 
971  **Deprecated:** For backwards compatibility, older config files
972  that use ``root="root"`` instead of ``root="config"`` will be
973  loaded with a warning printed to `sys.stderr`. This feature will be
974  removed at some point.
975 
976  See also
977  --------
978  lsst.pex.config.Config.loadFromStream
979  lsst.pex.config.Config.save
980  lsst.pex.config.Config.saveFromStream
981  """
982  with open(filename, "r") as f:
983  code = compile(f.read(), filename=filename, mode="exec")
984  self.loadFromStream(stream=code, root=root)
985 

◆ loadFromStream()

def pex.config.config.Config.loadFromStream (   self,
  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

Definition at line 986 of file config.py.

986  def loadFromStream(self, stream, root="config", filename=None):
987  """Modify this Config in place by executing the Python code in the
988  provided stream.
989 
990  Parameters
991  ----------
992  stream : file-like object, `str`, or compiled string
993  Stream containing configuration override code.
994  root : `str`, optional
995  Name of the variable in file that refers to the config being
996  overridden.
997 
998  For example, the value of root is ``"config"`` and the file
999  contains::
1000 
1001  config.myField = 5
1002 
1003  Then this config's field ``myField`` is set to ``5``.
1004 
1005  **Deprecated:** For backwards compatibility, older config files
1006  that use ``root="root"`` instead of ``root="config"`` will be
1007  loaded with a warning printed to `sys.stderr`. This feature will be
1008  removed at some point.
1009  filename : `str`, optional
1010  Name of the configuration file, or `None` if unknown or contained
1011  in the stream. Used for error reporting.
1012 
1013  See also
1014  --------
1015  lsst.pex.config.Config.load
1016  lsst.pex.config.Config.save
1017  lsst.pex.config.Config.saveFromStream
1018  """
1019  with RecordingImporter() as importer:
1020  try:
1021  local = {root: self}
1022  exec(stream, {}, local)
1023  except NameError as e:
1024  if root == "config" and "root" in e.args[0]:
1025  if filename is None:
1026  # try to determine the file name; a compiled string
1027  # has attribute "co_filename",
1028  # an open file has attribute "name", else give up
1029  filename = getattr(stream, "co_filename", None)
1030  if filename is None:
1031  filename = getattr(stream, "name", "?")
1032  print(f"Config override file {filename!r}"
1033  " appears to use 'root' instead of 'config'; trying with 'root'", file=sys.stderr)
1034  local = {"root": self}
1035  exec(stream, {}, local)
1036  else:
1037  raise
1038 
1039  self._imports.update(importer.getModules())
1040 

◆ names()

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

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

Definition at line 1167 of file config.py.

1167  def names(self):
1168  """Get all the field names in the config, recursively.
1169 
1170  Returns
1171  -------
1172  names : `list` of `str`
1173  Field names.
1174  """
1175  #
1176  # Rather than sort out the recursion all over again use the
1177  # pre-existing saveToStream()
1178  #
1179  with io.StringIO() as strFd:
1180  self.saveToStream(strFd, "config")
1181  contents = strFd.getvalue()
1182  strFd.close()
1183  #
1184  # Pull the names out of the dumped config
1185  #
1186  keys = []
1187  for line in contents.split("\n"):
1188  if re.search(r"^((assert|import)\s+|\s*$|#)", line):
1189  continue
1190 
1191  mat = re.search(r"^(?:config\.)?([^=]+)\s*=\s*.*", line)
1192  if mat:
1193  keys.append(mat.group(1))
1194 
1195  return keys
1196 

◆ save()

def 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.load
lsst.pex.config.Config.loadFromStream

Definition at line 1041 of file config.py.

1041  def save(self, filename, root="config"):
1042  """Save a Python script to the named file, which, when loaded,
1043  reproduces this config.
1044 
1045  Parameters
1046  ----------
1047  filename : `str`
1048  Desination filename of this configuration.
1049  root : `str`, optional
1050  Name to use for the root config variable. The same value must be
1051  used when loading (see `lsst.pex.config.Config.load`).
1052 
1053  See also
1054  --------
1055  lsst.pex.config.Config.saveToStream
1056  lsst.pex.config.Config.load
1057  lsst.pex.config.Config.loadFromStream
1058  """
1059  d = os.path.dirname(filename)
1060  with tempfile.NamedTemporaryFile(mode="w", delete=False, dir=d) as outfile:
1061  self.saveToStream(outfile, root)
1062  # tempfile is hardcoded to create files with mode '0600'
1063  # for an explantion of these antics see:
1064  # https://stackoverflow.com/questions/10291131/how-to-use-os-umask-in-python
1065  umask = os.umask(0o077)
1066  os.umask(umask)
1067  os.chmod(outfile.name, (~umask & 0o666))
1068  # chmod before the move so we get quasi-atomic behavior if the
1069  # source and dest. are on the same filesystem.
1070  # os.rename may not work across filesystems
1071  shutil.move(outfile.name, filename)
1072 

◆ saveToStream()

def pex.config.config.Config.saveToStream (   self,
  outfile,
  root = "config" 
)
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`).

See also
--------
lsst.pex.config.Config.save
lsst.pex.config.Config.load
lsst.pex.config.Config.loadFromStream

Definition at line 1073 of file config.py.

1073  def saveToStream(self, outfile, root="config"):
1074  """Save a configuration file to a stream, which, when loaded,
1075  reproduces this config.
1076 
1077  Parameters
1078  ----------
1079  outfile : file-like object
1080  Destination file object write the config into. Accepts strings not
1081  bytes.
1082  root
1083  Name to use for the root config variable. The same value must be
1084  used when loading (see `lsst.pex.config.Config.load`).
1085 
1086  See also
1087  --------
1088  lsst.pex.config.Config.save
1089  lsst.pex.config.Config.load
1090  lsst.pex.config.Config.loadFromStream
1091  """
1092  tmp = self._name
1093  self._rename(root)
1094  try:
1095  self._collectImports()
1096  # Remove self from the set, as it is handled explicitly below
1097  self._imports.remove(self.__module__)
1098  configType = type(self)
1099  typeString = _typeStr(configType)
1100  outfile.write(u"import {}\n".format(configType.__module__))
1101  outfile.write(u"assert type({})=={}, 'config is of type %s.%s ".format(root, typeString))
1102  outfile.write(u"instead of {}' % (type({}).__module__, type({}).__name__)\n".format(typeString,
1103  root,
1104  root))
1105  for imp in self._imports:
1106  if imp in sys.modules and sys.modules[imp] is not None:
1107  outfile.write(u"import {}\n".format(imp))
1108  self._save(outfile)
1109  finally:
1110  self._rename(tmp)
1111 
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
Definition: history.py:174
table::Key< int > type
Definition: Detector.cc:163

◆ setDefaults()

def 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``.

Definition at line 878 of file config.py.

878  def setDefaults(self):
879  """Subclass hook for computing defaults.
880 
881  Notes
882  -----
883  Derived `~lsst.pex.config.Config` classes that must compute defaults
884  rather than using the `~lsst.pex.config.Field` instances's defaults
885  should do so here. To correctly use inherited defaults,
886  implementations of ``setDefaults`` must call their base class's
887  ``setDefaults``.
888  """
889  pass
890 

◆ toDict()

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

Definition at line 1143 of file config.py.

1143  def toDict(self):
1144  """Make a dictionary of field names and their values.
1145 
1146  Returns
1147  -------
1148  dict_ : `dict`
1149  Dictionary with keys that are `~lsst.pex.config.Field` names.
1150  Values are `~lsst.pex.config.Field` values.
1151 
1152  See also
1153  --------
1154  lsst.pex.config.Field.toDict
1155 
1156  Notes
1157  -----
1158  This method uses the `~lsst.pex.config.Field.toDict` method of
1159  individual fields. Subclasses of `~lsst.pex.config.Field` may need to
1160  implement a ``toDict`` method for *this* method to work.
1161  """
1162  dict_ = {}
1163  for name, field in self._fields.items():
1164  dict_[name] = field.toDict(self)
1165  return dict_
1166 
std::vector< SchemaItem< Flag > > * items

◆ update()

def 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!'

Definition at line 891 of file config.py.

891  def update(self, **kw):
892  """Update values of fields specified by the keyword arguments.
893 
894  Parameters
895  ----------
896  kw
897  Keywords are configuration field names. Values are configuration
898  field values.
899 
900  Notes
901  -----
902  The ``__at`` and ``__label`` keyword arguments are special internal
903  keywords. They are used to strip out any internal steps from the
904  history tracebacks of the config. Do not modify these keywords to
905  subvert a `~lsst.pex.config.Config` instance's history.
906 
907  Examples
908  --------
909  This is a config with three fields:
910 
911  >>> from lsst.pex.config import Config, Field
912  >>> class DemoConfig(Config):
913  ... fieldA = Field(doc='Field A', dtype=int, default=42)
914  ... fieldB = Field(doc='Field B', dtype=bool, default=True)
915  ... fieldC = Field(doc='Field C', dtype=str, default='Hello world')
916  ...
917  >>> config = DemoConfig()
918 
919  These are the default values of each field:
920 
921  >>> for name, value in config.iteritems():
922  ... print(f"{name}: {value}")
923  ...
924  fieldA: 42
925  fieldB: True
926  fieldC: 'Hello world'
927 
928  Using this method to update ``fieldA`` and ``fieldC``:
929 
930  >>> config.update(fieldA=13, fieldC='Updated!')
931 
932  Now the values of each field are:
933 
934  >>> for name, value in config.iteritems():
935  ... print(f"{name}: {value}")
936  ...
937  fieldA: 13
938  fieldB: True
939  fieldC: 'Updated!'
940  """
941  at = kw.pop("__at", getCallStack())
942  label = kw.pop("__label", "update")
943 
944  for name, value in kw.items():
945  try:
946  field = self._fields[name]
947  field.__set__(self, value, at=at, label=label)
948  except KeyError:
949  raise KeyError("No field of name %s exists in config type %s" % (name, _typeStr(self)))
950 
def getCallStack(skip=0)
Definition: callStack.py:175

◆ validate()

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

Definition at line 1220 of file config.py.

1220  def validate(self):
1221  """Validate the Config, raising an exception if invalid.
1222 
1223  Raises
1224  ------
1225  lsst.pex.config.FieldValidationError
1226  Raised if verification fails.
1227 
1228  Notes
1229  -----
1230  The base class implementation performs type checks on all fields by
1231  calling their `~lsst.pex.config.Field.validate` methods.
1232 
1233  Complex single-field validation can be defined by deriving new Field
1234  types. For convenience, some derived `lsst.pex.config.Field`-types
1235  (`~lsst.pex.config.ConfigField` and
1236  `~lsst.pex.config.ConfigChoiceField`) are defined in `lsst.pex.config`
1237  that handle recursing into subconfigs.
1238 
1239  Inter-field relationships should only be checked in derived
1240  `~lsst.pex.config.Config` classes after calling this method, and base
1241  validation is complete.
1242  """
1243  for field in self._fields.values():
1244  field.validate(self)
1245 

◆ values()

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

Returns
-------
values : `list`
    List of field values.

See also
--------
lsst.pex.config.Config.itervalues

Definition at line 749 of file config.py.

749  def values(self):
750  """Get field values.
751 
752  Returns
753  -------
754  values : `list`
755  List of field values.
756 
757  See also
758  --------
759  lsst.pex.config.Config.itervalues
760  """
761  return list(self._storage.values())
762 
daf::base::PropertyList * list
Definition: fits.cc:903

Property Documentation

◆ history

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

Definition at line 1268 of file config.py.


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