28 __all__ = (
"Config",
"ConfigMeta",
"Field",
"FieldValidationError")
40 from .comparison
import getComparisonName, compareScalars, compareConfigs
41 from .callStack
import getStackFrame, getCallStack
44 def _joinNamePath(prefix=None, name=None, index=None):
45 """Generate nested configuration names.
47 if not prefix
and not name:
48 raise ValueError(
"Invalid name: cannot be None")
52 name = prefix +
"." + name
55 return "%s[%r]" % (name, index)
60 def _autocast(x, dtype):
61 """Cast a value to a type, if appropriate.
68 Data type, such as `float`, `int`, or `str`.
73 If appropriate, the returned value is ``x`` cast to the given type
74 ``dtype``. If the cast cannot be performed the original value of
77 if dtype == float
and isinstance(x, int):
83 """Generate a fully-qualified type name.
88 Fully-qualified type name.
92 This function is used primarily for writing config files to be executed
93 later upon with the 'load' function.
95 if hasattr(x,
'__module__')
and hasattr(x,
'__name__'):
99 if (sys.version_info.major <= 2
and xtype.__module__ ==
'__builtin__')
or xtype.__module__ ==
'builtins':
100 return xtype.__name__
102 return "%s.%s" % (xtype.__module__, xtype.__name__)
106 """A metaclass for `lsst.pex.config.Config`.
110 ``ConfigMeta`` adds a dictionary containing all `~lsst.pex.config.Field`
111 class attributes as a class attribute called ``_fields``, and adds
112 the name of each field as an instance variable of the field itself (so you
113 don't have to pass the name of the field to the field constructor).
117 type.__init__(cls, name, bases, dict_)
121 def getFields(classtype):
123 bases =
list(classtype.__bases__)
126 fields.update(getFields(b))
128 for k, v
in classtype.__dict__.items():
129 if isinstance(v, Field):
133 fields = getFields(cls)
134 for k, v
in fields.items():
135 setattr(cls, k, copy.deepcopy(v))
138 if isinstance(value, Field):
141 type.__setattr__(cls, name, value)
145 """Raised when a ``~lsst.pex.config.Field`` is not valid in a
146 particular ``~lsst.pex.config.Config``.
150 field : `lsst.pex.config.Field`
151 The field that was not valid.
152 config : `lsst.pex.config.Config`
153 The config containing the invalid field.
155 Text describing why the field was not valid.
160 """Type of the `~lsst.pex.config.Field` that incurred the error.
164 """Name of the `~lsst.pex.config.Field` instance that incurred the
169 lsst.pex.config.Field.name
172 self.
fullname = _joinNamePath(config._name, field.name)
173 """Fully-qualified name of the `~lsst.pex.config.Field` instance
177 self.
history = config.history.setdefault(field.name, [])
178 """Full history of all changes to the `~lsst.pex.config.Field`
183 """File and line number of the `~lsst.pex.config.Field` definition.
187 error =
"%s '%s' failed validation: %s\n"\
188 "For more information see the Field definition at:\n%s"\
189 " and the Config definition at:\n%s" % \
196 """A field in a `~lsst.pex.config.Config` that supports `int`, `float`,
197 `complex`, `bool`, and `str` data types.
202 A description of the field for users.
204 The field's data type. ``Field`` only supports basic data types:
205 `int`, `float`, `complex`, `bool`, and `str`. See
206 `Field.supportedTypes`.
207 default : object, optional
208 The field's default value.
209 check : callable, optional
210 A callable that is called with the field's value. This callable should
211 return `False` if the value is invalid. More complex inter-field
212 validation can be written as part of the
213 `lsst.pex.config.Config.validate` method.
214 optional : `bool`, optional
215 This sets whether the field is considered optional, and therefore
216 doesn't need to be set by the user. When `False`,
217 `lsst.pex.config.Config.validate` fails if the field's value is `None`.
218 deprecated : None or `str`, optional
219 A description of why this Field is deprecated, including removal date.
220 If not None, the string is appended to the docstring for this Field.
225 Raised when the ``dtype`` parameter is not one of the supported types
226 (see `Field.supportedTypes`).
242 ``Field`` instances (including those of any subclass of ``Field``) are used
243 as class attributes of `~lsst.pex.config.Config` subclasses (see the
244 example, below). ``Field`` attributes work like the `property` attributes
245 of classes that implement custom setters and getters. `Field` attributes
246 belong to the class, but operate on the instance. Formally speaking,
247 `Field` attributes are `descriptors
248 <https://docs.python.org/3/howto/descriptor.html>`_.
250 When you access a `Field` attribute on a `Config` instance, you don't
251 get the `Field` instance itself. Instead, you get the value of that field,
252 which might be a simple type (`int`, `float`, `str`, `bool`) or a custom
253 container type (like a `lsst.pex.config.List`) depending on the field's
254 type. See the example, below.
258 Instances of ``Field`` should be used as class attributes of
259 `lsst.pex.config.Config` subclasses:
261 >>> from lsst.pex.config import Config, Field
262 >>> class Example(Config):
263 ... myInt = Field("An integer field.", int, default=0)
265 >>> print(config.myInt)
268 >>> print(config.myInt)
272 supportedTypes =
set((str, bool, float, int, complex))
273 """Supported data types for field values (`set` of types).
276 def __init__(self, doc, dtype, default=None, check=None, optional=False, deprecated=None):
278 raise ValueError(
"Unsupported Field dtype %s" % _typeStr(dtype))
281 self.
_setup(doc=doc, dtype=dtype, default=default, check=check, optional=optional, source=source,
282 deprecated=deprecated)
284 def _setup(self, doc, dtype, default, check, optional, source, deprecated):
285 """Set attributes, usually during initialization.
288 """Data type for the field.
292 if deprecated
is not None:
293 doc = f
"{doc} Deprecated: {deprecated}"
295 """A description of the field (`str`).
299 """If not None, a description of why this field is deprecated (`str`).
302 self.
__doc__ = f
"{doc} (`{dtype.__name__}`"
303 if optional
or default
is not None:
304 self.
__doc__ += f
", default ``{default!r}``"
308 """Default value for this field.
312 """A user-defined function that validates the value of the field.
316 """Flag that determines if the field is required to be set (`bool`).
318 When `False`, `lsst.pex.config.Config.validate` will fail if the
319 field's value is `None`.
323 """The stack frame where this field is defined (`list` of
324 `lsst.pex.config.callStack.StackFrame`).
328 """Rename the field in a `~lsst.pex.config.Config` (for internal use
333 instance : `lsst.pex.config.Config`
334 The config instance that contains this field.
338 This method is invoked by the `lsst.pex.config.Config` object that
339 contains this field and should not be called directly.
341 Renaming is only relevant for `~lsst.pex.config.Field` instances that
342 hold subconfigs. `~lsst.pex.config.Fields` that hold subconfigs should
343 rename each subconfig with the full field name as generated by
344 `lsst.pex.config.config._joinNamePath`.
349 """Validate the field (for internal use only).
353 instance : `lsst.pex.config.Config`
354 The config instance that contains this field.
358 lsst.pex.config.FieldValidationError
359 Raised if verification fails.
363 This method provides basic validation:
365 - Ensures that the value is not `None` if the field is not optional.
366 - Ensures type correctness.
367 - Ensures that the user-provided ``check`` function is valid.
369 Most `~lsst.pex.config.Field` subclasses should call
370 `lsst.pex.config.field.Field.validate` if they re-implement
371 `~lsst.pex.config.field.Field.validate`.
373 value = self.__get__(instance)
374 if not self.optional
and value
is None:
375 raise FieldValidationError(self, instance,
"Required value cannot be None")
378 """Make this field read-only (for internal use only).
382 instance : `lsst.pex.config.Config`
383 The config instance that contains this field.
387 Freezing is only relevant for fields that hold subconfigs. Fields which
388 hold subconfigs should freeze each subconfig.
390 **Subclasses should implement this method.**
394 def _validateValue(self, value):
400 The value being validated.
405 Raised if the value's type is incompatible with the field's
408 Raised if the value is rejected by the ``check`` method.
413 if not isinstance(value, self.dtype):
414 msg =
"Value %s is of incorrect type %s. Expected type %s" % \
415 (value, _typeStr(value), _typeStr(self.dtype))
417 if self.check
is not None and not self.check(value):
418 msg =
"Value %s is not a valid value" % str(value)
419 raise ValueError(msg)
421 def _collectImports(self, instance, imports):
422 """This function should call the _collectImports method on all config
423 objects the field may own, and union them with the supplied imports
428 instance : instance or subclass of `lsst.pex.config.Config`
429 A config object that has this field defined on it
431 Set of python modules that need imported after persistence
435 def save(self, outfile, instance):
436 """Save this field to a file (for internal use only).
440 outfile : file-like object
441 A writeable field handle.
443 The `Config` instance that contains this field.
447 This method is invoked by the `~lsst.pex.config.Config` object that
448 contains this field and should not be called directly.
450 The output consists of the documentation string
451 (`lsst.pex.config.Field.doc`) formatted as a Python comment. The second
452 line is formatted as an assignment: ``{fullname}={value}``.
454 This output can be executed with Python.
456 value = self.__get__(instance)
457 fullname = _joinNamePath(instance._name, self.name)
459 if self.deprecated
and value == self.default:
464 doc =
"# " + str(self.doc).replace(
"\n",
"\n# ")
465 if isinstance(value, float)
and (math.isinf(value)
or math.isnan(value)):
467 outfile.write(
u"{}\n{}=float('{!r}')\n\n".
format(doc, fullname, value))
469 outfile.write(
u"{}\n{}={!r}\n\n".
format(doc, fullname, value))
472 """Convert the field value so that it can be set as the value of an
473 item in a `dict` (for internal use only).
478 The `Config` that contains this field.
483 The field's value. See *Notes*.
487 This method invoked by the owning `~lsst.pex.config.Config` object and
488 should not be called directly.
490 Simple values are passed through. Complex data structures must be
491 manipulated. For example, a `~lsst.pex.config.Field` holding a
492 subconfig should, instead of the subconfig object, return a `dict`
493 where the keys are the field names in the subconfig, and the values are
494 the field values in the subconfig.
498 def __get__(self, instance, owner=None, at=None, label="default"):
499 """Define how attribute access should occur on the Config instance
500 This is invoked by the owning config object and should not be called
503 When the field attribute is accessed on a Config class object, it
504 returns the field object itself in order to allow inspection of
507 When the field attribute is access on a config instance, the actual
508 value described by the field (and held by the Config instance) is
511 if instance
is None or not isinstance(instance, Config):
514 return instance._storage[self.name]
516 def __set__(self, instance, value, at=None, label='assignment'):
517 """Set an attribute on the config instance.
521 instance : `lsst.pex.config.Config`
522 The config instance that contains this field.
524 Value to set on this field.
525 at : `list` of `lsst.pex.config.callStack.StackFrame`
526 The call stack (created by
527 `lsst.pex.config.callStack.getCallStack`).
528 label : `str`, optional
529 Event label for the history.
533 This method is invoked by the owning `lsst.pex.config.Config` object
534 and should not be called directly.
536 Derived `~lsst.pex.config.Field` classes may need to override the
537 behavior. When overriding ``__set__``, `~lsst.pex.config.Field` authors
538 should follow the following rules:
540 - Do not allow modification of frozen configs.
541 - Validate the new value **before** modifying the field. Except if the
542 new value is `None`. `None` is special and no attempt should be made
543 to validate it until `lsst.pex.config.Config.validate` is called.
544 - Do not modify the `~lsst.pex.config.Config` instance to contain
546 - If the field is modified, update the history of the
547 `lsst.pex.config.field.Field` to reflect the changes.
549 In order to decrease the need to implement this method in derived
550 `~lsst.pex.config.Field` types, value validation is performed in the
551 `lsst.pex.config.Field._validateValue`. If only the validation step
552 differs in the derived `~lsst.pex.config.Field`, it is simpler to
553 implement `lsst.pex.config.Field._validateValue` than to reimplement
554 ``__set__``. More complicated behavior, however, may require
560 history = instance._history.setdefault(self.name, [])
561 if value
is not None:
562 value = _autocast(value, self.
dtype)
565 except BaseException
as e:
568 instance._storage[self.name] = value
571 history.append((value, at, label))
574 """Delete an attribute from a `lsst.pex.config.Config` instance.
578 instance : `lsst.pex.config.Config`
579 The config instance that contains this field.
580 at : `list` of `lsst.pex.config.callStack.StackFrame`
581 The call stack (created by
582 `lsst.pex.config.callStack.getCallStack`).
583 label : `str`, optional
584 Event label for the history.
588 This is invoked by the owning `~lsst.pex.config.Config` object and
589 should not be called directly.
593 self.
__set__(instance,
None, at=at, label=label)
595 def _compare(self, instance1, instance2, shortcut, rtol, atol, output):
596 """Compare a field (named `Field.name`) in two
597 `~lsst.pex.config.Config` instances for equality.
601 instance1 : `lsst.pex.config.Config`
602 Left-hand side `Config` instance to compare.
603 instance2 : `lsst.pex.config.Config`
604 Right-hand side `Config` instance to compare.
605 shortcut : `bool`, optional
607 rtol : `float`, optional
608 Relative tolerance for floating point comparisons.
609 atol : `float`, optional
610 Absolute tolerance for floating point comparisons.
611 output : callable, optional
612 A callable that takes a string, used (possibly repeatedly) to
617 This method must be overridden by more complex `Field` subclasses.
621 lsst.pex.config.compareScalars
623 v1 = getattr(instance1, self.name)
624 v2 = getattr(instance2, self.name)
626 _joinNamePath(instance1._name, self.name),
627 _joinNamePath(instance2._name, self.name)
633 """Importer (for `sys.meta_path`) that records which modules are being
636 *This class does not do any importing itself.*
640 Use this class as a context manager to ensure it is properly uninstalled
643 >>> with RecordingImporter() as importer:
645 ... import numpy as np
646 ... print("Imported: " + importer.getModules())
654 sys.meta_path = [self] + sys.meta_path
662 """Uninstall the importer.
667 """Called as part of the ``import`` chain of events.
674 """Get the set of modules that were imported.
678 modules : `set` of `str`
679 Set of imported module names.
685 """Base class for configuration (*config*) objects.
689 A ``Config`` object will usually have several `~lsst.pex.config.Field`
690 instances as class attributes. These are used to define most of the base
693 ``Config`` implements a mapping API that provides many `dict`-like methods,
694 such as `keys`, `values`, `items`, `iteritems`, `iterkeys`, and
695 `itervalues`. ``Config`` instances also support the ``in`` operator to
696 test if a field is in the config. Unlike a `dict`, ``Config`` classes are
697 not subscriptable. Instead, access individual fields as attributes of the
698 configuration instance.
702 Config classes are subclasses of ``Config`` that have
703 `~lsst.pex.config.Field` instances (or instances of
704 `~lsst.pex.config.Field` subclasses) as class attributes:
706 >>> from lsst.pex.config import Config, Field, ListField
707 >>> class DemoConfig(Config):
708 ... intField = Field(doc="An integer field", dtype=int, default=42)
709 ... listField = ListField(doc="List of favorite beverages.", dtype=str,
710 ... default=['coffee', 'green tea', 'water'])
712 >>> config = DemoConfig()
714 Configs support many `dict`-like APIs:
717 ['intField', 'listField']
718 >>> 'intField' in config
721 Individual fields can be accessed as attributes of the configuration:
725 >>> config.listField.append('earl grey tea')
726 >>> print(config.listField)
727 ['coffee', 'green tea', 'water', 'earl grey tea']
731 """Iterate over fields.
741 List of `lsst.pex.config.Field` names.
745 lsst.pex.config.Config.iterkeys
755 List of field values.
759 lsst.pex.config.Config.itervalues
764 """Get configurations as ``(field name, field value)`` pairs.
769 List of tuples for each configuration. Tuple items are:
776 lsst.pex.config.Config.iteritems
781 """Iterate over (field name, field value) pairs.
793 lsst.pex.config.Config.items
798 """Iterate over field values.
807 lsst.pex.config.Config.values
812 """Iterate over field names
817 A field's key (attribute name).
821 lsst.pex.config.Config.values
826 """!Return True if the specified field exists in this config
828 @param[in] name field name to test for
833 """Allocate a new `lsst.pex.config.Config` object.
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
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.
844 name = kw.pop(
"__name",
None)
847 kw.pop(
"__label",
"default")
849 instance = object.__new__(cls)
850 instance._frozen =
False
851 instance._name = name
852 instance._storage = {}
853 instance._history = {}
854 instance._imports =
set()
856 for field
in instance._fields.values():
857 instance._history[field.name] = []
858 field.__set__(instance, field.default, at=at + [field.source], label=
"default")
860 instance.setDefaults()
862 instance.update(__at=at, **kw)
866 """Reduction for pickling (function with arguments to reproduce).
868 We need to condense and reconstitute the `~lsst.pex.config.Config`,
869 since it may contain lambdas (as the ``check`` elements) that cannot
874 stream = io.StringIO()
876 return (unreduceConfig, (self.__class__, stream.getvalue().encode()))
879 """Subclass hook for computing defaults.
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
892 """Update values of fields specified by the keyword arguments.
897 Keywords are configuration field names. Values are configuration
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.
909 This is a config with three fields:
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')
917 >>> config = DemoConfig()
919 These are the default values of each field:
921 >>> for name, value in config.iteritems():
922 ... print(f"{name}: {value}")
926 fieldC: 'Hello world'
928 Using this method to update ``fieldA`` and ``fieldC``:
930 >>> config.update(fieldA=13, fieldC='Updated!')
932 Now the values of each field are:
934 >>> for name, value in config.iteritems():
935 ... print(f"{name}: {value}")
942 label = kw.pop(
"__label",
"update")
944 for name, value
in kw.items():
946 field = self._fields[name]
947 field.__set__(self, value, at=at, label=label)
949 raise KeyError(
"No field of name %s exists in config type %s" % (name, _typeStr(self)))
951 def load(self, filename, root="config"):
952 """Modify this config in place by executing the Python code in a
958 Name of the configuration file. A configuration file is Python
960 root : `str`, optional
961 Name of the variable in file that refers to the config being
964 For example, the value of root is ``"config"`` and the file
969 Then this config's field ``myField`` is set to ``5``.
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.
978 lsst.pex.config.Config.loadFromStream
979 lsst.pex.config.Config.save
980 lsst.pex.config.Config.saveFromStream
982 with open(filename,
"r")
as f:
983 code = compile(f.read(), filename=filename, mode=
"exec")
987 """Modify this Config in place by executing the Python code in the
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
998 For example, the value of root is ``"config"`` and the file
1003 Then this config's field ``myField`` is set to ``5``.
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.
1015 lsst.pex.config.Config.load
1016 lsst.pex.config.Config.save
1017 lsst.pex.config.Config.saveFromStream
1020 globals = {
"__file__": filename}
1022 local = {root: self}
1023 exec(stream, globals, local)
1024 except NameError
as e:
1025 if root ==
"config" and "root" in e.args[0]:
1026 if filename
is None:
1030 filename = getattr(stream,
"co_filename",
None)
1031 if filename
is None:
1032 filename = getattr(stream,
"name",
"?")
1033 print(f
"Config override file {filename!r}"
1034 " appears to use 'root' instead of 'config'; trying with 'root'", file=sys.stderr)
1035 local = {
"root": self}
1036 exec(stream, globals, local)
1040 self._imports.
update(importer.getModules())
1042 def save(self, filename, root="config"):
1043 """Save a Python script to the named file, which, when loaded,
1044 reproduces this config.
1049 Desination filename of this configuration.
1050 root : `str`, optional
1051 Name to use for the root config variable. The same value must be
1052 used when loading (see `lsst.pex.config.Config.load`).
1056 lsst.pex.config.Config.saveToStream
1057 lsst.pex.config.Config.load
1058 lsst.pex.config.Config.loadFromStream
1060 d = os.path.dirname(filename)
1061 with tempfile.NamedTemporaryFile(mode=
"w", delete=
False, dir=d)
as outfile:
1066 umask = os.umask(0o077)
1068 os.chmod(outfile.name, (~umask & 0o666))
1072 shutil.move(outfile.name, filename)
1075 """Save a configuration file to a stream, which, when loaded,
1076 reproduces this config.
1080 outfile : file-like object
1081 Destination file object write the config into. Accepts strings not
1084 Name to use for the root config variable. The same value must be
1085 used when loading (see `lsst.pex.config.Config.load`).
1086 skipImports : `bool`, optional
1087 If `True` then do not include ``import`` statements in output,
1088 this is to support human-oriented output from ``pipetask`` where
1089 additional clutter is not useful.
1093 lsst.pex.config.Config.save
1094 lsst.pex.config.Config.load
1095 lsst.pex.config.Config.loadFromStream
1103 self._imports.remove(self.__module__)
1104 configType =
type(self)
1105 typeString = _typeStr(configType)
1106 outfile.write(f
"import {configType.__module__}\n")
1107 outfile.write(f
"assert type({root})=={typeString}, 'config is of type %s.%s instead of "
1108 f
"{typeString}' % (type({root}).__module__, type({root}).__name__)\n")
1109 for imp
in self._imports:
1110 if imp
in sys.modules
and sys.modules[imp]
is not None:
1111 outfile.write(
u"import {}\n".
format(imp))
1117 """Make this config, and all subconfigs, read-only.
1123 def _save(self, outfile):
1124 """Save this config to an open stream object.
1128 outfile : file-like object
1129 Destination file object write the config into. Accepts strings not
1133 field.save(outfile, self)
1135 def _collectImports(self):
1136 """Adds module containing self to the list of things to import and
1137 then loops over all the fields in the config calling a corresponding
1138 collect method. The field method will call _collectImports on any
1139 configs it may own and return the set of things to import. This
1140 returned set will be merged with the set of imports for this config
1143 self._imports.add(self.__module__)
1145 field._collectImports(self, self._imports)
1148 """Make a dictionary of field names and their values.
1153 Dictionary with keys that are `~lsst.pex.config.Field` names.
1154 Values are `~lsst.pex.config.Field` values.
1158 lsst.pex.config.Field.toDict
1162 This method uses the `~lsst.pex.config.Field.toDict` method of
1163 individual fields. Subclasses of `~lsst.pex.config.Field` may need to
1164 implement a ``toDict`` method for *this* method to work.
1168 dict_[name] = field.toDict(self)
1172 """Get all the field names in the config, recursively.
1176 names : `list` of `str`
1183 with io.StringIO()
as strFd:
1185 contents = strFd.getvalue()
1191 for line
in contents.split(
"\n"):
1192 if re.search(
r"^((assert|import)\s+|\s*$|#)", line):
1195 mat = re.search(
r"^(?:config\.)?([^=]+)\s*=\s*.*", line)
1197 keys.append(mat.group(1))
1201 def _rename(self, name):
1202 """Rename this config object in its parent `~lsst.pex.config.Config`.
1207 New name for this config in its parent `~lsst.pex.config.Config`.
1211 This method uses the `~lsst.pex.config.Field.rename` method of
1212 individual `lsst.pex.config.Field` instances.
1213 `lsst.pex.config.Field` subclasses may need to implement a ``rename``
1214 method for *this* method to work.
1218 lsst.pex.config.Field.rename
1225 """Validate the Config, raising an exception if invalid.
1229 lsst.pex.config.FieldValidationError
1230 Raised if verification fails.
1234 The base class implementation performs type checks on all fields by
1235 calling their `~lsst.pex.config.Field.validate` methods.
1237 Complex single-field validation can be defined by deriving new Field
1238 types. For convenience, some derived `lsst.pex.config.Field`-types
1239 (`~lsst.pex.config.ConfigField` and
1240 `~lsst.pex.config.ConfigChoiceField`) are defined in `lsst.pex.config`
1241 that handle recursing into subconfigs.
1243 Inter-field relationships should only be checked in derived
1244 `~lsst.pex.config.Config` classes after calling this method, and base
1245 validation is complete.
1248 field.validate(self)
1251 """Format a configuration field's history to a human-readable format.
1256 Name of a `~lsst.pex.config.Field` in this config.
1258 Keyword arguments passed to `lsst.pex.config.history.format`.
1263 A string containing the formatted history.
1267 lsst.pex.config.history.format
1269 import lsst.pex.config.history
as pexHist
1270 return pexHist.format(self, name, **kwargs)
1272 history = property(
lambda x: x._history)
1273 """Read-only history.
1277 """Set an attribute (such as a field's value).
1281 Unlike normal Python objects, `~lsst.pex.config.Config` objects are
1282 locked such that no additional attributes nor properties may be added
1283 to them dynamically.
1285 Although this is not the standard Python behavior, it helps to protect
1286 users from accidentally mispelling a field name, or trying to set a
1290 if self.
_fields[attr].deprecated
is not None:
1291 fullname = _joinNamePath(self.
_name, self.
_fields[attr].name)
1292 warnings.warn(f
"Config field {fullname} is deprecated: {self._fields[attr].deprecated}",
1293 FutureWarning, stacklevel=2)
1297 self.
_fields[attr].__set__(self, value, at=at, label=label)
1298 elif hasattr(getattr(self.__class__, attr,
None),
'__set__'):
1300 return object.__setattr__(self, attr, value)
1301 elif attr
in self.__dict__
or attr
in (
"_name",
"_history",
"_storage",
"_frozen",
"_imports"):
1303 self.__dict__[attr] = value
1306 raise AttributeError(
"%s has no attribute %s" % (_typeStr(self), attr))
1312 self.
_fields[attr].__delete__(self, at=at, label=label)
1314 object.__delattr__(self, attr)
1319 thisValue = getattr(self, name)
1320 otherValue = getattr(other, name)
1321 if isinstance(thisValue, float)
and math.isnan(thisValue):
1322 if not math.isnan(otherValue):
1324 elif thisValue != otherValue:
1330 return not self.
__eq__(other)
1333 return str(self.
toDict())
1338 ", ".join(
"%s=%r" % (k, v)
for k, v
in self.
toDict().
items()
if v
is not None)
1341 def compare(self, other, shortcut=True, rtol=1E-8, atol=1E-8, output=None):
1342 """Compare this configuration to another `~lsst.pex.config.Config` for
1347 other : `lsst.pex.config.Config`
1348 Other `~lsst.pex.config.Config` object to compare against this
1350 shortcut : `bool`, optional
1351 If `True`, return as soon as an inequality is found. Default is
1353 rtol : `float`, optional
1354 Relative tolerance for floating point comparisons.
1355 atol : `float`, optional
1356 Absolute tolerance for floating point comparisons.
1357 output : callable, optional
1358 A callable that takes a string, used (possibly repeatedly) to
1359 report inequalities.
1364 `True` when the two `lsst.pex.config.Config` instances are equal.
1365 `False` if there is an inequality.
1369 lsst.pex.config.compareConfigs
1373 Unselected targets of `~lsst.pex.config.RegistryField` fields and
1374 unselected choices of `~lsst.pex.config.ConfigChoiceField` fields
1375 are not considered by this method.
1377 Floating point comparisons are performed by `numpy.allclose`.
1379 name1 = self.
_name if self.
_name is not None else "config"
1380 name2 = other._name
if other._name
is not None else "config"
1383 rtol=rtol, atol=atol, output=output)
1387 """Create a `~lsst.pex.config.Config` from a stream.
1391 cls : `lsst.pex.config.Config`-type
1392 A `lsst.pex.config.Config` type (not an instance) that is instantiated
1393 with configurations in the ``stream``.
1394 stream : file-like object, `str`, or compiled string
1395 Stream containing configuration override code.
1399 config : `lsst.pex.config.Config`
1404 lsst.pex.config.Config.loadFromStream
1407 config.loadFromStream(stream)