Coverage for python/lsst/pex/config/config.py : 61%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# # LSST Data Management System # Copyright 2008-2015 AURA/LSST. # # This product includes software developed by the # LSST Project (http://www.lsst.org/). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the LSST License Statement and # the GNU General Public License along with this program. If not, # see <https://www.lsstcorp.org/LegalNotices/>. #
""" Utility function for generating nested configuration names """ raise ValueError("Invalid name: cannot be None") name = prefix
return "%s[%r]" % (name, index) else:
""" If appropriate perform type casting of value x to type dtype, otherwise return the original value x """
""" Utility function to generate a fully qualified type name.
This is used primarily in writing config files to be executed later upon 'load'. """ else: return xtype.__name__ else:
"""A metaclass for Config
Adds a dictionary containing all Field class attributes as a class attribute called '_fields', and adds the name of each field as an instance variable of the field itself (so you don't have to pass the name of the field to the field constructor). """
""" Custom exception class which holds additional information useful to debuggin Config errors: - fieldType: type of the Field which incurred the error - fieldName: name of the Field which incurred the error - fullname: fully qualified name of the Field instance - history: full history of all changes to the Field instance - fieldSource: file and line number of the Field definition """ self.fieldType = type(field) self.fieldName = field.name self.fullname = _joinNamePath(config._name, field.name) self.history = config.history.setdefault(field.name, []) self.fieldSource = field.source self.configSource = config._source error = "%s '%s' failed validation: %s\n"\ "For more information read the Field definition at:\n%s"\ "And the Config definition at:\n%s" % \ (self.fieldType.__name__, self.fullname, msg, self.fieldSource.format(), self.configSource.format()) ValueError.__init__(self, error)
"""A field in a a Config.
Instances of Field should be class attributes of Config subclasses: Field only supports basic data types (int, float, complex, bool, str)
class Example(Config): myInt = Field(int, "an integer field!", default=0) """ # Must be able to support str and future str as we can not guarantee that # code will pass in a future str type on Python 2
"""Initialize a Field.
dtype ------ Data type for the field. doc -------- Documentation for the field. default ---- A default value for the field. check ------ A callable to be called with the field value that returns False if the value is invalid. More complex inter-field validation can be written as part of Config validate() method; this will be ignored if set to None. optional --- When False, Config validate() will fail if value is None """ raise ValueError("Unsupported Field dtype %s" % _typeStr(dtype))
""" Convenience function provided to simplify initialization of derived Field types """
""" Rename an instance of this field, not the field itself. This is invoked by the owning config object and should not be called directly
Only useful for fields which hold sub-configs. Fields which hold subconfigs should rename each sub-config with the full field name as generated by _joinNamePath """
""" Base validation for any field. Ensures that non-optional fields are not None. Ensures type correctness Ensures that user-provided check function is valid Most derived Field types should call Field.validate if they choose to re-implement validate """ value = self.__get__(instance) if not self.optional and value is None: raise FieldValidationError(self, instance, "Required value cannot be None")
""" Make this field read-only. Only important for fields which hold sub-configs. Fields which hold subconfigs should freeze each sub-config. """ pass
""" Validate a value that is not None
This is called from __set__ This is not part of the Field API. However, simple derived field types may benefit from implementing _validateValue """ return
msg = "Value %s is of incorrect type %s. Expected type %s" % \ (value, _typeStr(value), _typeStr(self.dtype)) raise TypeError(msg) msg = "Value %s is not a valid value" % str(value) raise ValueError(msg)
""" Saves an instance of this field to file. This is invoked by the owning config object, and should not be called directly
outfile ---- an open output stream. """
# write full documentation string as comment lines (i.e. first character is #) # non-finite numbers need special care outfile.write(u"{}\n{}=float('{!r}')\n\n".format(doc, fullname, value)) else:
""" Convert the field value so that it can be set as the value of an item in a dict. This is invoked by the owning config object and should not be called directly
Simple values are passed through. Complex data structures must be manipulated. For example, a field holding a sub-config should, instead of the subconfig object, return a dict where the keys are the field names in the subconfig, and the values are the field values in the subconfig. """
""" Define how attribute access should occur on the Config instance This is invoked by the owning config object and should not be called directly
When the field attribute is accessed on a Config class object, it returns the field object itself in order to allow inspection of Config classes.
When the field attribute is access on a config instance, the actual value described by the field (and held by the Config instance) is returned. """ return self else:
""" Describe how attribute setting should occur on the config instance. This is invoked by the owning config object and should not be called directly
Derived Field classes may need to override the behavior. When overriding __set__, Field authors should follow the following rules: * Do not allow modification of frozen configs * Validate the new value *BEFORE* modifying the field. Except if the new value is None. None is special and no attempt should be made to validate it until Config.validate is called. * Do not modify the Config instance to contain invalid values. * If the field is modified, update the history of the field to reflect the changes
In order to decrease the need to implement this method in derived Field types, value validation is performed in the method _validateValue. If only the validation step differs in the derived Field, it is simpler to implement _validateValue than to re-implement __set__. More complicated behavior, however, may require a reimplementation. """ raise FieldValidationError(self, instance, "Cannot modify a frozen Config")
except BaseException as e: raise FieldValidationError(self, instance, str(e))
at = getCallStack()
""" Describe how attribute deletion should occur on the Config instance. This is invoked by the owning config object and should not be called directly """ if at is None: at = getCallStack() self.__set__(instance, None, at=at, label=label)
"""Helper function for Config.compare; used to compare two fields for equality.
Must be overridden by more complex field types.
@param[in] instance1 LHS Config instance to compare. @param[in] instance2 RHS Config instance to compare. @param[in] shortcut If True, return as soon as an inequality is found. @param[in] rtol Relative tolerance for floating point comparisons. @param[in] atol Absolute tolerance for floating point comparisons. @param[in] output If not None, a callable that takes a string, used (possibly repeatedly) to report inequalities.
Floating point comparisons are performed by numpy.allclose; refer to that for details. """ v1 = getattr(instance1, self.name) v2 = getattr(instance2, self.name) name = getComparisonName( _joinNamePath(instance1._name, self.name), _joinNamePath(instance2._name, self.name) ) return compareScalars(name, v1, v2, dtype=self.dtype, rtol=rtol, atol=atol, output=output)
"""An Importer (for sys.meta_path) that records which modules are being imported.
Objects also act as Context Managers, so you can: with RecordingImporter() as importer: import stuff print("Imported: " + importer.getModules()) This ensures it is properly uninstalled when done.
This class makes no effort to do any importing itself. """ """Create and install the Importer"""
"""Uninstall the Importer"""
"""Called as part of the 'import' chain of events.
We return None because we don't do any importing. """ self._modules.add(fullname) return None
"""Return the set of modules that were imported."""
"""Base class for control objects.
A Config object will usually have several Field instances as class attributes; these are used to define most of the base class behavior. Simple derived class should be able to be defined simply by setting those attributes.
Config also emulates a dict of field name: field value """
"""!Iterate over fields """ return self._fields.__iter__()
"""!Return the list of field names """ return list(self._storage.keys())
"""!Return the list of field values """ return list(self._storage.values())
"""!Return the list of (field name, field value) pairs """ return list(self._storage.items())
"""!Iterate over (field name, field value) pairs """ return iter(self._storage.items())
"""!Iterate over field values """ return iter(self.storage.values())
"""!Iterate over field names """ return iter(self.storage.keys())
"""!Return True if the specified field exists in this config
@param[in] name field name to test for """ return self._storage.__contains__(name)
"""!Allocate a new Config object.
In order to ensure that all Config object are always in a proper state when handed to users or to derived Config classes, some attributes are handled at allocation time rather than at initialization
This ensures that even if a derived Config class implements __init__, the author does not need to be concerned about when or even if he should call the base Config.__init__ """ # remove __label and ignore it
# load up defaults # set custom default-overides # set constructor overides
"""Reduction for pickling (function with arguments to reproduce).
We need to condense and reconstitute the Config, since it may contain lambdas (as the 'check' elements) that cannot be pickled. """ # The stream must be in characters to match the API but pickle requires bytes
""" Derived config classes that must compute defaults rather than using the Field defaults should do so here. To correctly use inherited defaults, implementations of setDefaults() must call their base class' setDefaults() """
"""!Update values specified by the keyword arguments
@warning 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. Modifying these keywords allows users to lie about a Config's history. Please do not do so! """
except KeyError: raise KeyError("No field of name %s exists in config type %s" % (name, _typeStr(self)))
"""!Modify this config in place by executing the Python code in the named file.
@param[in] filename name of file containing config override code @param[in] root name of variable in file that refers to the config being overridden
For example: if the value of root is "config" and the file contains this text: "config.myField = 5" then this config's field "myField" is set to 5.
@deprecated For purposes of 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. """ with open(filename, "r") as f: code = compile(f.read(), filename=filename, mode="exec") self.loadFromStream(stream=code, root=root)
"""!Modify this config in place by executing the python code in the provided stream.
@param[in] stream open file object, string or compiled string containing config override code @param[in] root name of variable in stream that refers to the config being overridden @param[in] filename name of config override file, or None if unknown or contained in the stream; used for error reporting
For example: if the value of root is "config" and the stream contains this text: "config.myField = 5" then this config's field "myField" is set to 5.
@deprecated For purposes of 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. """ except NameError as e: if root == "config" and "root" in e.args[0]: if filename is None: # try to determine the file name; a compiled string has attribute "co_filename", # an open file has attribute "name", else give up filename = getattr(stream, "co_filename", None) if filename is None: filename = getattr(stream, "name", "?") print(f"Config override file {filename!r}" " appears to use 'root' instead of 'config'; trying with 'root'", file=sys.stderr) local = {"root": self} exec(stream, {}, local) else: raise
"""!Save a python script to the named file, which, when loaded, reproduces this Config
@param[in] filename name of file to which to write the config @param[in] root name to use for the root config variable; the same value must be used when loading """ d = os.path.dirname(filename) with tempfile.NamedTemporaryFile(mode="w", delete=False, dir=d) as outfile: self.saveToStream(outfile, root) # tempfile is hardcoded to create files with mode '0600' # for an explantion of these antics see: # https://stackoverflow.com/questions/10291131/how-to-use-os-umask-in-python umask = os.umask(0o077) os.umask(umask) os.chmod(outfile.name, (~umask & 0o666)) # chmod before the move so we get quasi-atomic behavior if the # source and dest. are on the same filesystem. # os.rename may not work across filesystems shutil.move(outfile.name, filename)
"""!Save a python script to a stream, which, when loaded, reproduces this Config
@param outfile [inout] open file object to which to write the config. Accepts strings not bytes. @param root [in] name to use for the root config variable; the same value must be used when loading """ root, root)) finally:
"""!Make this Config and all sub-configs read-only """ self._frozen = True for field in self._fields.values(): field.freeze(self)
"""!Save this Config to an open stream object """ if imp in sys.modules and sys.modules[imp] is not None: outfile.write(u"import {}\n".format(imp))
"""!Return a dict of field name: value
Correct behavior is dependent on proper implementation of Field.toDict. If implementing a new Field type, you may need to implement your own toDict method. """
"""!Return all the keys in a config recursively """ # # Rather than sort out the recursion all over again use the # pre-existing saveToStream() # with io.StringIO() as strFd: self.saveToStream(strFd, "config") contents = strFd.getvalue() strFd.close() # # Pull the names out of the dumped config # keys = [] for line in contents.split("\n"): if re.search(r"^((assert|import)\s+|\s*$|#)", line): continue
mat = re.search(r"^(?:config\.)?([^=]+)\s*=\s*.*", line) if mat: keys.append(mat.group(1))
return keys
"""!Rename this Config object in its parent config
@param[in] name new name for this config in its parent config
Correct behavior is dependent on proper implementation of Field.rename. If implementing a new Field type, you may need to implement your own rename method. """
"""!Validate the Config; raise an exception if invalid
The base class implementation performs type checks on all fields by calling Field.validate().
Complex single-field validation can be defined by deriving new Field types. As syntactic sugar, some derived Field types are defined in this module which handle recursing into sub-configs (ConfigField, ConfigChoiceField)
Inter-field relationships should only be checked in derived Config classes after calling this method, and base validation is complete """ for field in self._fields.values(): field.validate(self)
"""!Format the specified config field's history to a more human-readable format
@param[in] name name of field whose history is wanted @param[in] kwargs keyword arguments for lsst.pex.config.history.format @return a string containing the formatted history """ import lsst.pex.config.history as pexHist return pexHist.format(self, name, **kwargs)
""" Read-only history property """
"""!Regulate which attributes can be set
Unlike normal python objects, 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. """ # This allows Field descriptors to work. # This allows properties and other non-Field descriptors to work. return object.__setattr__(self, attr, value) # This allows specific private attributes to work. else: # We throw everything else. raise AttributeError("%s has no attribute %s" % (_typeStr(self), attr))
if attr in self._fields: if at is None: at = getCallStack() self._fields[attr].__delete__(self, at=at, label=label) else: object.__delattr__(self, attr)
for name in self._fields: thisValue = getattr(self, name) otherValue = getattr(other, name) if isinstance(thisValue, float) and math.isnan(thisValue): if not math.isnan(otherValue): return False elif thisValue != otherValue: return False return True
return str(self.toDict())
_typeStr(self), ", ".join("%s=%r" % (k, v) for k, v in self.toDict().items() if v is not None) )
"""!Compare two Configs for equality; return True if equal
If the Configs contain RegistryFields or ConfigChoiceFields, unselected Configs will not be compared.
@param[in] other Config object to compare with self. @param[in] shortcut If True, return as soon as an inequality is found. @param[in] rtol Relative tolerance for floating point comparisons. @param[in] atol Absolute tolerance for floating point comparisons. @param[in] output If not None, a callable that takes a string, used (possibly repeatedly) to report inequalities.
Floating point comparisons are performed by numpy.allclose; refer to that for details. """ name1 = self._name if self._name is not None else "config" name2 = other._name if other._name is not None else "config" name = getComparisonName(name1, name2) return compareConfigs(name, self, other, shortcut=shortcut, rtol=rtol, atol=atol, output=output)
|