lsst.pipe.base  18.1.0-4-g6c9d669
configOverrides.py
Go to the documentation of this file.
1 # This file is part of pipe_base.
2 #
3 # Developed for the LSST Data Management System.
4 # This product includes software developed by the LSST Project
5 # (http://www.lsst.org).
6 # See the COPYRIGHT file at the top-level directory of this distribution
7 # for details of code ownership.
8 #
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 
22 """Module which defines ConfigOverrides class and related methods.
23 """
24 
25 __all__ = ["ConfigOverrides"]
26 
27 import ast
28 
29 import lsst.pex.exceptions as pexExceptions
30 
31 
33  """Defines a set of overrides to be applied to a task config.
34 
35  Overrides for task configuration need to be applied by activator when
36  creating task instances. This class represents an ordered set of such
37  overrides which activator receives from some source (e.g. command line
38  or some other configuration).
39 
40  Methods
41  ----------
42  addFileOverride(filename)
43  Add overrides from a specified file.
44  addValueOverride(field, value)
45  Add override for a specific field.
46  applyTo(config)
47  Apply all overrides to a `config` instance.
48 
49  Notes
50  -----
51  Serialization support for this class may be needed, will add later if
52  necessary.
53  """
54 
55  def __init__(self):
56  self._overrides = []
57 
58  def addFileOverride(self, filename):
59  """Add overrides from a specified file.
60 
61  Parameters
62  ----------
63  filename : str
64  Path to the override file.
65  """
66  self._overrides += [('file', filename)]
67 
68  def addValueOverride(self, field, value):
69  """Add override for a specific field.
70 
71  This method is not very type-safe as it is designed to support
72  use cases where input is given as string, e.g. command line
73  activators. If `value` has a string type and setting of the field
74  fails with `TypeError` the we'll attempt `eval()` the value and
75  set the field with that value instead.
76 
77  Parameters
78  ----------
79  field : str
80  Fully-qualified field name.
81  value :
82  Value to be given to a filed.
83  """
84  self._overrides += [('value', (field, value))]
85 
86  def applyTo(self, config):
87  """Apply all overrides to a task configuration object.
88 
89  Parameters
90  ----------
91  config : `pex.Config`
92 
93  Raises
94  ------
95  `Exception` is raised if operations on configuration object fail.
96  """
97  for otype, override in self._overrides:
98  if otype == 'file':
99  config.load(override)
100  elif otype == 'value':
101  field, value = override
102  field = field.split('.')
103  # find object with attribute to set, throws if we name is wrong
104  obj = config
105  for attr in field[:-1]:
106  obj = getattr(obj, attr)
107  # If input is a string and field type is not a string then we
108  # have to convert string to an expected type. Implementing
109  # full string parser is non-trivial so we take a shortcut here
110  # and `eval` the string and assign the resulting value to a
111  # field. Type erroes can happen during both `eval` and field
112  # assignment.
113  if isinstance(value, str) and obj._fields[field[-1]].dtype is not str:
114  try:
115  # use safer ast.literal_eval, it only supports literals
116  value = ast.literal_eval(value)
117  except Exception:
118  # eval failed, wrap exception with more user-friendly message
119  raise pexExceptions.RuntimeError(f"Unable to parse `{value}' into a Python object")
120 
121  # this can throw in case of type mismatch
122  setattr(obj, field[-1], value)