LSSTApplications  11.0-13-gbb96280,12.1+18,12.1+7,12.1-1-g14f38d3+72,12.1-1-g16c0db7+5,12.1-1-g5961e7a+84,12.1-1-ge22e12b+23,12.1-11-g06625e2+4,12.1-11-g0d7f63b+4,12.1-19-gd507bfc,12.1-2-g7dda0ab+38,12.1-2-gc0bc6ab+81,12.1-21-g6ffe579+2,12.1-21-gbdb6c2a+4,12.1-24-g941c398+5,12.1-3-g57f6835+7,12.1-3-gf0736f3,12.1-37-g3ddd237,12.1-4-gf46015e+5,12.1-5-g06c326c+20,12.1-5-g648ee80+3,12.1-5-gc2189d7+4,12.1-6-ga608fc0+1,12.1-7-g3349e2a+5,12.1-7-gfd75620+9,12.1-9-g577b946+5,12.1-9-gc4df26a+10
LSSTDataManagementBasePackage
config.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2008-2015 AURA/LSST.
4 #
5 # This product includes software developed by the
6 # LSST Project (http://www.lsst.org/).
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the LSST License Statement and
19 # the GNU General Public License along with this program. If not,
20 # see <https://www.lsstcorp.org/LegalNotices/>.
21 #
22 oldStringType = str # Need to keep hold of original str type
23 from builtins import str
24 from builtins import object
25 from past.builtins import long
26 
27 import os
28 import io
29 import traceback
30 import sys
31 import math
32 import copy
33 import tempfile
34 import shutil
35 
36 from .comparison import getComparisonName, compareScalars, compareConfigs
37 from future.utils import with_metaclass
38 
39 __all__ = ("Config", "Field", "FieldValidationError")
40 
41 
42 def _joinNamePath(prefix=None, name=None, index=None):
43  """
44  Utility function for generating nested configuration names
45  """
46  if not prefix and not name:
47  raise ValueError("Invalid name: cannot be None")
48  elif not name:
49  name = prefix
50  elif prefix and name:
51  name = prefix + "." + name
52 
53  if index is not None:
54  return "%s[%r]" % (name, index)
55  else:
56  return name
57 
58 
59 def _autocast(x, dtype):
60  """
61  If appropriate perform type casting of value x to type dtype,
62  otherwise return the original value x
63  """
64  if dtype == float and isinstance(x, int):
65  return float(x)
66  if dtype == int and isinstance(x, long):
67  return int(x)
68  if isinstance(x, str):
69  return oldStringType(x)
70  return x
71 
72 
73 def _typeStr(x):
74  """
75  Utility function to generate a fully qualified type name.
76 
77  This is used primarily in writing config files to be
78  executed later upon 'load'.
79  """
80  if hasattr(x, '__module__') and hasattr(x, '__name__'):
81  xtype = x
82  else:
83  xtype = type(x)
84  if (sys.version_info.major <= 2 and xtype.__module__ == '__builtin__') or xtype.__module__ == 'builtins':
85  return xtype.__name__
86  else:
87  return "%s.%s" % (xtype.__module__, xtype.__name__)
88 
89 
90 class ConfigMeta(type):
91  """A metaclass for Config
92 
93  Adds a dictionary containing all Field class attributes
94  as a class attribute called '_fields', and adds the name of each field as
95  an instance variable of the field itself (so you don't have to pass the
96  name of the field to the field constructor).
97  """
98  def __init__(self, name, bases, dict_):
99  type.__init__(self, name, bases, dict_)
100  self._fields = {}
101  self._source = traceback.extract_stack(limit=2)[0]
102 
103  def getFields(classtype):
104  fields = {}
105  bases = list(classtype.__bases__)
106  bases.reverse()
107  for b in bases:
108  fields.update(getFields(b))
109 
110  for k, v in classtype.__dict__.items():
111  if isinstance(v, Field):
112  fields[k] = v
113  return fields
114 
115  fields = getFields(self)
116  for k, v in fields.items():
117  setattr(self, k, copy.deepcopy(v))
118 
119  def __setattr__(self, name, value):
120  if isinstance(value, Field):
121  value.name = name
122  self._fields[name] = value
123  type.__setattr__(self, name, value)
124 
125 
126 class FieldValidationError(ValueError):
127  """
128  Custom exception class which holds additional information useful to
129  debuggin Config errors:
130  - fieldType: type of the Field which incurred the error
131  - fieldName: name of the Field which incurred the error
132  - fullname: fully qualified name of the Field instance
133  - history: full history of all changes to the Field instance
134  - fieldSource: file and line number of the Field definition
135  """
136  def __init__(self, field, config, msg):
137  self.fieldType = type(field)
138  self.fieldName = field.name
139  self.fullname = _joinNamePath(config._name, field.name)
140  self.history = config.history.setdefault(field.name, [])
141  self.fieldSource = field.source
142  self.configSource = config._source
143  error = "%s '%s' failed validation: %s\n"\
144  "For more information read the Field definition at:\n%s"\
145  "And the Config definition at:\n%s" % \
146  (self.fieldType.__name__, self.fullname, msg,
147  traceback.format_list([self.fieldSource])[0],
148  traceback.format_list([self.configSource])[0])
149  ValueError.__init__(self, error)
150 
151 
152 class Field(object):
153  """A field in a a Config.
154 
155  Instances of Field should be class attributes of Config subclasses:
156  Field only supports basic data types (int, float, complex, bool, str)
157 
158  class Example(Config):
159  myInt = Field(int, "an integer field!", default=0)
160  """
161  # Must be able to support str and future str as we can not guarantee that
162  # code will pass in a future str type on Python 2
163  supportedTypes = set((str, oldStringType, bool, float, int, complex))
164 
165  def __init__(self, doc, dtype, default=None, check=None, optional=False):
166  """Initialize a Field.
167 
168  dtype ------ Data type for the field.
169  doc -------- Documentation for the field.
170  default ---- A default value for the field.
171  check ------ A callable to be called with the field value that returns
172  False if the value is invalid. More complex inter-field
173  validation can be written as part of Config validate()
174  method; this will be ignored if set to None.
175  optional --- When False, Config validate() will fail if value is None
176  """
177  if dtype not in self.supportedTypes:
178  raise ValueError("Unsupported Field dtype %s" % _typeStr(dtype))
179 
180  # Use standard string type if we are given a future str
181  if dtype == str:
182  dtype = oldStringType
183 
184  source = traceback.extract_stack(limit=2)[0]
185  self._setup(doc=doc, dtype=dtype, default=default, check=check, optional=optional, source=source)
186 
187  def _setup(self, doc, dtype, default, check, optional, source):
188  """
189  Convenience function provided to simplify initialization of derived
190  Field types
191  """
192  self.dtype = dtype
193  self.doc = doc
194  self.__doc__ = doc
195  self.default = default
196  self.check = check
197  self.optional = optional
198  self.source = source
199 
200  def rename(self, instance):
201  """
202  Rename an instance of this field, not the field itself.
203  This is invoked by the owning config object and should not be called
204  directly
205 
206  Only useful for fields which hold sub-configs.
207  Fields which hold subconfigs should rename each sub-config with
208  the full field name as generated by _joinNamePath
209  """
210  pass
211 
212  def validate(self, instance):
213  """
214  Base validation for any field.
215  Ensures that non-optional fields are not None.
216  Ensures type correctness
217  Ensures that user-provided check function is valid
218  Most derived Field types should call Field.validate if they choose
219  to re-implement validate
220  """
221  value = self.__get__(instance)
222  if not self.optional and value is None:
223  raise FieldValidationError(self, instance, "Required value cannot be None")
224 
225  def freeze(self, instance):
226  """
227  Make this field read-only.
228  Only important for fields which hold sub-configs.
229  Fields which hold subconfigs should freeze each sub-config.
230  """
231  pass
232 
233  def _validateValue(self, value):
234  """
235  Validate a value that is not None
236 
237  This is called from __set__
238  This is not part of the Field API. However, simple derived field types
239  may benifit from implementing _validateValue
240  """
241  if value is None:
242  return
243 
244  if not isinstance(value, self.dtype):
245  msg = "Value %s is of incorrect type %s. Expected type %s" % \
246  (value, _typeStr(value), _typeStr(self.dtype))
247  raise TypeError(msg)
248  if self.check is not None and not self.check(value):
249  msg = "Value %s is not a valid value" % str(value)
250  raise ValueError(msg)
251 
252  def save(self, outfile, instance):
253  """
254  Saves an instance of this field to file.
255  This is invoked by the owning config object, and should not be called
256  directly
257 
258  outfile ---- an open output stream.
259  """
260  value = self.__get__(instance)
261  fullname = _joinNamePath(instance._name, self.name)
262 
263  # write full documentation string as comment lines (i.e. first character is #)
264  doc = "# " + str(self.doc).replace("\n", "\n# ")
265  if isinstance(value, float) and (math.isinf(value) or math.isnan(value)):
266  # non-finite numbers need special care
267  outfile.write(u"{}\n{}=float('{!r}')\n\n".format(doc, fullname, value))
268  else:
269  outfile.write(u"{}\n{}={!r}\n\n".format(doc, fullname, value))
270 
271  def toDict(self, instance):
272  """
273  Convert the field value so that it can be set as the value of an item
274  in a dict.
275  This is invoked by the owning config object and should not be called
276  directly
277 
278  Simple values are passed through. Complex data structures must be
279  manipulated. For example, a field holding a sub-config should, instead
280  of the subconfig object, return a dict where the keys are the field
281  names in the subconfig, and the values are the field values in the
282  subconfig.
283  """
284  return self.__get__(instance)
285 
286  def __get__(self, instance, owner=None, at=None, label="default"):
287  """
288  Define how attribute access should occur on the Config instance
289  This is invoked by the owning config object and should not be called
290  directly
291 
292  When the field attribute is accessed on a Config class object, it
293  returns the field object itself in order to allow inspection of
294  Config classes.
295 
296  When the field attribute is access on a config instance, the actual
297  value described by the field (and held by the Config instance) is
298  returned.
299  """
300  if instance is None or not isinstance(instance, Config):
301  return self
302  else:
303  return instance._storage[self.name]
304 
305  def __set__(self, instance, value, at=None, label='assignment'):
306  """
307  Describe how attribute setting should occur on the config instance.
308  This is invoked by the owning config object and should not be called
309  directly
310 
311  Derived Field classes may need to override the behavior. When overriding
312  __set__, Field authors should follow the following rules:
313  * Do not allow modification of frozen configs
314  * Validate the new value *BEFORE* modifying the field. Except if the
315  new value is None. None is special and no attempt should be made to
316  validate it until Config.validate is called.
317  * Do not modify the Config instance to contain invalid values.
318  * If the field is modified, update the history of the field to reflect the
319  changes
320 
321  In order to decrease the need to implement this method in derived Field
322  types, value validation is performed in the method _validateValue. If
323  only the validation step differs in the derived Field, it is simpler to
324  implement _validateValue than to re-implement __set__. More complicated
325  behavior, however, may require a reimplementation.
326  """
327  if instance._frozen:
328  raise FieldValidationError(self, instance, "Cannot modify a frozen Config")
329 
330  history = instance._history.setdefault(self.name, [])
331  if value is not None:
332  value = _autocast(value, self.dtype)
333  try:
334  self._validateValue(value)
335  except BaseException as e:
336  raise FieldValidationError(self, instance, str(e))
337 
338  instance._storage[self.name] = value
339  if at is None:
340  at = traceback.extract_stack()[:-1]
341  history.append((value, at, label))
342 
343  def __delete__(self, instance, at=None, label='deletion'):
344  """
345  Describe how attribute deletion should occur on the Config instance.
346  This is invoked by the owning config object and should not be called
347  directly
348  """
349  if at is None:
350  at = traceback.extract_stack()[:-1]
351  self.__set__(instance, None, at=at, label=label)
352 
353  def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
354  """Helper function for Config.compare; used to compare two fields for equality.
355 
356  Must be overridden by more complex field types.
357 
358  @param[in] instance1 LHS Config instance to compare.
359  @param[in] instance2 RHS Config instance to compare.
360  @param[in] shortcut If True, return as soon as an inequality is found.
361  @param[in] rtol Relative tolerance for floating point comparisons.
362  @param[in] atol Absolute tolerance for floating point comparisons.
363  @param[in] output If not None, a callable that takes a string, used (possibly repeatedly)
364  to report inequalities.
365 
366  Floating point comparisons are performed by numpy.allclose; refer to that for details.
367  """
368  v1 = getattr(instance1, self.name)
369  v2 = getattr(instance2, self.name)
370  name = getComparisonName(
371  _joinNamePath(instance1._name, self.name),
372  _joinNamePath(instance2._name, self.name)
373  )
374  return compareScalars(name, v1, v2, dtype=self.dtype, rtol=rtol, atol=atol, output=output)
375 
376 
377 class RecordingImporter(object):
378  """An Importer (for sys.meta_path) that records which modules are being imported.
379 
380  Objects also act as Context Managers, so you can:
381  with RecordingImporter() as importer:
382  import stuff
383  print("Imported: " + importer.getModules())
384  This ensures it is properly uninstalled when done.
385 
386  This class makes no effort to do any importing itself.
387  """
388  def __init__(self):
389  """Create and install the Importer"""
390  self._modules = set()
391 
392  def __enter__(self):
393 
394  self.origMetaPath = sys.meta_path
395  sys.meta_path = [self] + sys.meta_path
396  return self
397 
398  def __exit__(self, *args):
399  self.uninstall()
400  return False # Don't suppress exceptions
401 
402  def uninstall(self):
403  """Uninstall the Importer"""
404  sys.meta_path = self.origMetaPath
405 
406  def find_module(self, fullname, path=None):
407  """Called as part of the 'import' chain of events.
408 
409  We return None because we don't do any importing.
410  """
411  self._modules.add(fullname)
412  return None
413 
414  def getModules(self):
415  """Return the set of modules that were imported."""
416  return self._modules
417 
418 
419 class Config(with_metaclass(ConfigMeta, object)):
420  """Base class for control objects.
421 
422  A Config object will usually have several Field instances as class
423  attributes; these are used to define most of the base class behavior.
424  Simple derived class should be able to be defined simply by setting those
425  attributes.
426 
427  Config also emulates a dict of field name: field value
428  """
429 
430  def __iter__(self):
431  """!Iterate over fields
432  """
433  return self._fields.__iter__()
434 
435  def keys(self):
436  """!Return the list of field names
437  """
438  return list(self._storage.keys())
439 
440  def values(self):
441  """!Return the list of field values
442  """
443  return list(self._storage.values())
444 
445  def items(self):
446  """!Return the list of (field name, field value) pairs
447  """
448  return list(self._storage.items())
449 
450  def iteritems(self):
451  """!Iterate over (field name, field value) pairs
452  """
453  return iter(self._storage.items())
454 
455  def itervalues(self):
456  """!Iterate over field values
457  """
458  return iter(self.storage.values())
459 
460  def iterkeys(self):
461  """!Iterate over field names
462  """
463  return iter(self.storage.keys())
464 
465  def __contains__(self, name):
466  """!Return True if the specified field exists in this config
467 
468  @param[in] name field name to test for
469  """
470  return self._storage.__contains__(name)
471 
472  def __new__(cls, *args, **kw):
473  """!Allocate a new Config object.
474 
475  In order to ensure that all Config object are always in a proper
476  state when handed to users or to derived Config classes, some
477  attributes are handled at allocation time rather than at initialization
478 
479  This ensures that even if a derived Config class implements __init__,
480  the author does not need to be concerned about when or even if he
481  should call the base Config.__init__
482  """
483  name = kw.pop("__name", None)
484  at = kw.pop("__at", traceback.extract_stack()[:-1])
485  # remove __label and ignore it
486  kw.pop("__label", "default")
487 
488  instance = object.__new__(cls)
489  instance._frozen = False
490  instance._name = name
491  instance._storage = {}
492  instance._history = {}
493  instance._imports = set()
494  # load up defaults
495  for field in instance._fields.values():
496  instance._history[field.name] = []
497  field.__set__(instance, field.default, at=at+[field.source], label="default")
498  # set custom default-overides
499  instance.setDefaults()
500  # set constructor overides
501  instance.update(__at=at, **kw)
502  return instance
503 
504  def __reduce__(self):
505  """Reduction for pickling (function with arguments to reproduce).
506 
507  We need to condense and reconstitute the Config, since it may contain lambdas
508  (as the 'check' elements) that cannot be pickled.
509  """
510  # The stream must be in characters to match the API but pickle requires bytes
511  stream = io.StringIO()
512  self.saveToStream(stream)
513  return (unreduceConfig, (self.__class__, stream.getvalue().encode()))
514 
515  def setDefaults(self):
516  """
517  Derived config classes that must compute defaults rather than using the
518  Field defaults should do so here.
519  To correctly use inherited defaults, implementations of setDefaults()
520  must call their base class' setDefaults()
521  """
522  pass
523 
524  def update(self, **kw):
525  """!Update values specified by the keyword arguments
526 
527  @warning The '__at' and '__label' keyword arguments are special internal
528  keywords. They are used to strip out any internal steps from the
529  history tracebacks of the config. Modifying these keywords allows users
530  to lie about a Config's history. Please do not do so!
531  """
532  at = kw.pop("__at", traceback.extract_stack()[:-1])
533  label = kw.pop("__label", "update")
534 
535  for name, value in kw.items():
536  try:
537  field = self._fields[name]
538  field.__set__(self, value, at=at, label=label)
539  except KeyError:
540  raise KeyError("No field of name %s exists in config type %s" % (name, _typeStr(self)))
541 
542  def load(self, filename, root="config"):
543  """!Modify this config in place by executing the Python code in the named file.
544 
545  @param[in] filename name of file containing config override code
546  @param[in] root name of variable in file that refers to the config being overridden
547 
548  For example: if the value of root is "config" and the file contains this text:
549  "config.myField = 5" then this config's field "myField" is set to 5.
550 
551  @deprecated For purposes of backwards compatibility, older config files that use
552  root="root" instead of root="config" will be loaded with a warning printed to sys.stderr.
553  This feature will be removed at some point.
554  """
555  with open(filename, "r") as f:
556  code = compile(f.read(), filename=filename, mode="exec")
557  self.loadFromStream(stream=code, root=root)
558 
559  def loadFromStream(self, stream, root="config", filename=None):
560  """!Modify this config in place by executing the python code in the provided stream.
561 
562  @param[in] stream open file object, string or compiled string containing config override code
563  @param[in] root name of variable in stream that refers to the config being overridden
564  @param[in] filename name of config override file, or None if unknown or contained
565  in the stream; used for error reporting
566 
567  For example: if the value of root is "config" and the stream contains this text:
568  "config.myField = 5" then this config's field "myField" is set to 5.
569 
570  @deprecated For purposes of backwards compatibility, older config files that use
571  root="root" instead of root="config" will be loaded with a warning printed to sys.stderr.
572  This feature will be removed at some point.
573  """
574  with RecordingImporter() as importer:
575  try:
576  local = {root: self}
577  exec(stream, {}, local)
578  except NameError as e:
579  if root == "config" and "root" in e.args[0]:
580  if filename is None:
581  # try to determine the file name; a compiled string has attribute "co_filename",
582  # an open file has attribute "name", else give up
583  filename = getattr(stream, "co_filename", None)
584  if filename is None:
585  filename = getattr(stream, "name", "?")
586  sys.stderr.write(u"Config override file %r" % (filename,) +
587  u" appears to use 'root' instead of 'config'; trying with 'root'")
588  local = {"root": self}
589  exec(stream, {}, local)
590  else:
591  raise
592 
593  self._imports.update(importer.getModules())
594 
595  def save(self, filename, root="config"):
596  """!Save a python script to the named file, which, when loaded, reproduces this Config
597 
598  @param[in] filename name of file to which to write the config
599  @param[in] root name to use for the root config variable; the same value must be used when loading
600  """
601  d = os.path.dirname(filename)
602  with tempfile.NamedTemporaryFile(mode="w", delete=False, dir=d) as outfile:
603  self.saveToStream(outfile, root)
604  # tempfile is hardcoded to create files with mode '0600'
605  # for an explantion of these antics see:
606  # https://stackoverflow.com/questions/10291131/how-to-use-os-umask-in-python
607  umask = os.umask(0o077)
608  os.umask(umask)
609  os.chmod(outfile.name, (~umask & 0o666))
610  # chmod before the move so we get quasi-atomic behavior if the
611  # source and dest. are on the same filesystem.
612  # os.rename may not work across filesystems
613  shutil.move(outfile.name, filename)
614 
615  def saveToStream(self, outfile, root="config"):
616  """!Save a python script to a stream, which, when loaded, reproduces this Config
617 
618  @param outfile [inout] open file object to which to write the config. Accepts strings not bytes.
619  @param root [in] name to use for the root config variable; the same value must be used when loading
620  """
621  tmp = self._name
622  self._rename(root)
623  try:
624  configType = type(self)
625  typeString = _typeStr(configType)
626  outfile.write(u"import {}\n".format(configType.__module__))
627  outfile.write(u"assert type({})=={}, 'config is of type %s.%s ".format(root, typeString))
628  outfile.write(u"instead of {}' % (type({}).__module__, type({}).__name__)\n".format(typeString,
629  root,
630  root))
631  self._save(outfile)
632  finally:
633  self._rename(tmp)
634 
635  def freeze(self):
636  """!Make this Config and all sub-configs read-only
637  """
638  self._frozen = True
639  for field in self._fields.values():
640  field.freeze(self)
641 
642  def _save(self, outfile):
643  """!Save this Config to an open stream object
644  """
645  for imp in self._imports:
646  if imp in sys.modules and sys.modules[imp] is not None:
647  outfile.write(u"import {}\n".format(imp))
648  for field in self._fields.values():
649  field.save(outfile, self)
650 
651  def toDict(self):
652  """!Return a dict of field name: value
653 
654  Correct behavior is dependent on proper implementation of Field.toDict. If implementing a new
655  Field type, you may need to implement your own toDict method.
656  """
657  dict_ = {}
658  for name, field in self._fields.items():
659  dict_[name] = field.toDict(self)
660  return dict_
661 
662  def _rename(self, name):
663  """!Rename this Config object in its parent config
664 
665  @param[in] name new name for this config in its parent config
666 
667  Correct behavior is dependent on proper implementation of Field.rename. If implementing a new
668  Field type, you may need to implement your own rename method.
669  """
670  self._name = name
671  for field in self._fields.values():
672  field.rename(self)
673 
674  def validate(self):
675  """!Validate the Config; raise an exception if invalid
676 
677  The base class implementation performs type checks on all fields by
678  calling Field.validate().
679 
680  Complex single-field validation can be defined by deriving new Field
681  types. As syntactic sugar, some derived Field types are defined in
682  this module which handle recursing into sub-configs
683  (ConfigField, ConfigChoiceField)
684 
685  Inter-field relationships should only be checked in derived Config
686  classes after calling this method, and base validation is complete
687  """
688  for field in self._fields.values():
689  field.validate(self)
690 
691  def formatHistory(self, name, **kwargs):
692  """!Format the specified config field's history to a more human-readable format
693 
694  @param[in] name name of field whose history is wanted
695  @param[in] kwargs keyword arguments for lsst.pex.config.history.format
696  @return a string containing the formatted history
697  """
698  import lsst.pex.config.history as pexHist
699  return pexHist.format(self, name, **kwargs)
700 
701  """
702  Read-only history property
703  """
704  history = property(lambda x: x._history)
705 
706  def __setattr__(self, attr, value, at=None, label="assignment"):
707  """!Regulate which attributes can be set
708 
709  Unlike normal python objects, Config objects are locked such
710  that no additional attributes nor properties may be added to them
711  dynamically.
712 
713  Although this is not the standard Python behavior, it helps to
714  protect users from accidentally mispelling a field name, or
715  trying to set a non-existent field.
716  """
717  if attr in self._fields:
718  if at is None:
719  at = traceback.extract_stack()[:-1]
720  # This allows Field descriptors to work.
721  self._fields[attr].__set__(self, value, at=at, label=label)
722  elif hasattr(getattr(self.__class__, attr, None), '__set__'):
723  # This allows properties and other non-Field descriptors to work.
724  return object.__setattr__(self, attr, value)
725  elif attr in self.__dict__ or attr in ("_name", "_history", "_storage", "_frozen", "_imports"):
726  # This allows specific private attributes to work.
727  self.__dict__[attr] = value
728  else:
729  # We throw everything else.
730  raise AttributeError("%s has no attribute %s" % (_typeStr(self), attr))
731 
732  def __delattr__(self, attr, at=None, label="deletion"):
733  if attr in self._fields:
734  if at is None:
735  at = traceback.extract_stack()[:-1]
736  self._fields[attr].__delete__(self, at=at, label=label)
737  else:
738  object.__delattr__(self, attr)
739 
740  def __eq__(self, other):
741  if type(other) == type(self):
742  for name in self._fields:
743  thisValue = getattr(self, name)
744  otherValue = getattr(other, name)
745  if isinstance(thisValue, float) and math.isnan(thisValue):
746  if not math.isnan(otherValue):
747  return False
748  elif thisValue != otherValue:
749  return False
750  return True
751  return False
752 
753  def __ne__(self, other):
754  return not self.__eq__(other)
755 
756  def __str__(self):
757  return str(self.toDict())
758 
759  def __repr__(self):
760  return "%s(%s)" % (
761  _typeStr(self),
762  ", ".join("%s=%r" % (k, v) for k, v in self.toDict().items() if v is not None)
763  )
764 
765  def compare(self, other, shortcut=True, rtol=1E-8, atol=1E-8, output=None):
766  """!Compare two Configs for equality; return True if equal
767 
768  If the Configs contain RegistryFields or ConfigChoiceFields, unselected Configs
769  will not be compared.
770 
771  @param[in] other Config object to compare with self.
772  @param[in] shortcut If True, return as soon as an inequality is found.
773  @param[in] rtol Relative tolerance for floating point comparisons.
774  @param[in] atol Absolute tolerance for floating point comparisons.
775  @param[in] output If not None, a callable that takes a string, used (possibly repeatedly)
776  to report inequalities.
777 
778  Floating point comparisons are performed by numpy.allclose; refer to that for details.
779  """
780  name1 = self._name if self._name is not None else "config"
781  name2 = other._name if other._name is not None else "config"
782  name = getComparisonName(name1, name2)
783  return compareConfigs(name, self, other, shortcut=shortcut,
784  rtol=rtol, atol=atol, output=output)
785 
786 
787 def unreduceConfig(cls, stream):
788  config = cls()
789  config.loadFromStream(stream)
790  return config
int iter
def keys
Return the list of field names.
Definition: config.py:435
def __setattr__
Regulate which attributes can be set.
Definition: config.py:706
def freeze
Make this Config and all sub-configs read-only.
Definition: config.py:635
def saveToStream
Save a python script to a stream, which, when loaded, reproduces this Config.
Definition: config.py:615
def loadFromStream
Modify this config in place by executing the python code in the provided stream.
Definition: config.py:559
def compare
Compare two Configs for equality; return True if equal.
Definition: config.py:765
def iteritems
Iterate over (field name, field value) pairs.
Definition: config.py:450
def __contains__
Return True if the specified field exists in this config.
Definition: config.py:465
def save
Save a python script to the named file, which, when loaded, reproduces this Config.
Definition: config.py:595
def _rename
Rename this Config object in its parent config.
Definition: config.py:662
def _save
Save this Config to an open stream object.
Definition: config.py:642
def load
Modify this config in place by executing the Python code in the named file.
Definition: config.py:542
def itervalues
Iterate over field values.
Definition: config.py:455
def iterkeys
Iterate over field names.
Definition: config.py:460
def toDict
Return a dict of field name: value.
Definition: config.py:651
def __iter__
Iterate over fields.
Definition: config.py:430
def formatHistory
Format the specified config field&#39;s history to a more human-readable format.
Definition: config.py:691
def items
Return the list of (field name, field value) pairs.
Definition: config.py:445
def update
Update values specified by the keyword arguments.
Definition: config.py:524
def validate
Validate the Config; raise an exception if invalid.
Definition: config.py:674
def __new__
Allocate a new Config object.
Definition: config.py:472
def values
Return the list of field values.
Definition: config.py:440