예제 #1
0
    def validateItem(self, i, x):
        """Validate an item to determine if it can be included in the list.

        Parameters
        ----------
        i : `int`
            Index of the item in the `list`.
        x : object
            Item in the `list`.

        Raises
        ------
        FieldValidationError
            Raised if an item in the ``value`` parameter does not have the
            appropriate type for this field or does not pass the field's
            `ListField.itemCheck` method.
        """

        if not isinstance(x, self._field.itemtype) and x is not None:
            msg = "Item at position %d with value %s is of incorrect type %s. Expected %s" % \
                (i, x, _typeStr(x), _typeStr(self._field.itemtype))
            raise FieldValidationError(self._field, self._config, msg)

        if self._field.itemCheck is not None and not self._field.itemCheck(x):
            msg = "Item at position %d is not a valid value: %s" % (i, x)
            raise FieldValidationError(self._field, self._config, msg)
    def __setitem__(self, k, value, at=None, label="assignment"):
        if self._config._frozen:
            raise FieldValidationError(self._field, self._config,
                                       "Cannot modify a frozen Config")

        try:
            dtype = self.types[k]
        except Exception:
            raise FieldValidationError(self._field, self._config,
                                       "Unknown key %r" % k)

        if value != dtype and type(value) != dtype:
            msg = "Value %s at key %s is of incorrect type %s. Expected type %s" % \
                (value, k, _typeStr(value), _typeStr(dtype))
            raise FieldValidationError(self._field, self._config, msg)

        if at is None:
            at = getCallStack()
        name = _joinNamePath(self._config._name, self._field.name, k)
        oldValue = self._dict.get(k, None)
        if oldValue is None:
            if value == dtype:
                self._dict[k] = value(__name=name, __at=at, __label=label)
            else:
                self._dict[k] = dtype(__name=name,
                                      __at=at,
                                      __label=label,
                                      **value._storage)
        else:
            if value == dtype:
                value = value()
            oldValue.update(__at=at, __label=label, **value._storage)
    def __init__(self,
                 dict_,
                 value,
                 at=None,
                 label="assignment",
                 setHistory=True):
        if at is None:
            at = getCallStack()
        self._dict = dict_
        self._field = self._dict._field
        self._config = self._dict._config
        self.__history = self._config._history.setdefault(self._field.name, [])
        if value is not None:
            try:
                for v in value:
                    if v not in self._dict:
                        # invoke __getitem__ to ensure it's present
                        self._dict.__getitem__(v, at=at)
            except TypeError:
                msg = "Value %s is of incorrect type %s. Sequence type expected" % (
                    value, _typeStr(value))
                raise FieldValidationError(self._field, self._config, msg)
            self._set = set(value)
        else:
            self._set = set()

        if setHistory:
            self.__history.append(("Set selection to %s" % self, at, label))
    def validate(self, instance):
        value = self.__get__(instance)
        value.validate()

        if self.check is not None and not self.check(value):
            msg = "%s is not a valid value" % str(value)
            raise FieldValidationError(self, instance, msg)
예제 #5
0
 def __delitem__(self, i, at=None, label="delitem", setHistory=True):
     if self._config._frozen:
         raise FieldValidationError(self._field, self._config,
                                    "Cannot modify a frozen Config")
     del self._list[i]
     if setHistory:
         if at is None:
             at = getCallStack()
         self.history.append((list(self._list), at, label))
예제 #6
0
    def validate(self, instance):
        """Validate the field.

        Parameters
        ----------
        instance : `lsst.pex.config.Config`
            The config instance that contains this field.

        Raises
        ------
        lsst.pex.config.FieldValidationError
            Raised if:

            - The field is not optional, but the value is `None`.
            - The list itself does not meet the requirements of the `length`,
              `minLength`, or `maxLength` attributes.
            - The `listCheck` callable returns `False`.

        Notes
        -----
        Individual item checks (`itemCheck`) are applied when each item is
        set and are not re-checked by this method.
        """
        Field.validate(self, instance)
        value = self.__get__(instance)
        if value is not None:
            lenValue = len(value)
            if self.length is not None and not lenValue == self.length:
                msg = "Required list length=%d, got length=%d" % (self.length,
                                                                  lenValue)
                raise FieldValidationError(self, instance, msg)
            elif self.minLength is not None and lenValue < self.minLength:
                msg = "Minimum allowed list length=%d, got length=%d" % (
                    self.minLength, lenValue)
                raise FieldValidationError(self, instance, msg)
            elif self.maxLength is not None and lenValue > self.maxLength:
                msg = "Maximum allowed list length=%d, got length=%d" % (
                    self.maxLength, lenValue)
                raise FieldValidationError(self, instance, msg)
            elif self.listCheck is not None and not self.listCheck(value):
                msg = "%s is not a valid value" % str(value)
                raise FieldValidationError(self, instance, msg)
    def __set__(self, instance, value, at=None, label="assignment"):
        if instance._frozen:
            raise FieldValidationError(self, instance,
                                       "Cannot modify a frozen Config")
        if at is None:
            at = getCallStack()
        oldValue = self.__getOrMake(instance, at=at)

        if isinstance(value, ConfigurableInstance):
            oldValue.retarget(value.target, value.ConfigClass, at, label)
            oldValue.update(__at=at, __label=label, **value._storage)
        elif type(value) == oldValue._ConfigClass:
            oldValue.update(__at=at, __label=label, **value._storage)
        elif value == oldValue.ConfigClass:
            value = oldValue.ConfigClass()
            oldValue.update(__at=at, __label=label, **value._storage)
        else:
            msg = "Value %s is of incorrect type %s. Expected %s" % \
                (value, _typeStr(value), _typeStr(oldValue.ConfigClass))
            raise FieldValidationError(self, instance, msg)
 def validate(self, instance):
     instanceDict = self.__get__(instance)
     if instanceDict.active is None and not self.optional:
         msg = "Required field cannot be None"
         raise FieldValidationError(self, instance, msg)
     elif instanceDict.active is not None:
         if self.multi:
             for a in instanceDict.active:
                 a.validate()
         else:
             instanceDict.active.validate()
예제 #9
0
 def __setattr__(self, attr, value, at=None, label="assignment"):
     if hasattr(getattr(self.__class__, attr, None), '__set__'):
         # This allows properties to work.
         object.__setattr__(self, attr, value)
     elif attr in self.__dict__ or attr in [
             "_field", "_config", "_history", "_list", "__doc__"
     ]:
         # This allows specific private attributes to work.
         object.__setattr__(self, attr, value)
     else:
         # We throw everything else.
         msg = "%s has no attribute %s" % (_typeStr(self._field), attr)
         raise FieldValidationError(self._field, self._config, msg)
    def __set__(self, instance, value, at=None, label="assignment"):
        if instance._frozen:
            raise FieldValidationError(self, instance,
                                       "Cannot modify a frozen Config")
        if at is None:
            at = getCallStack()
        instanceDict = self._getOrMake(instance)
        if isinstance(value, self.instanceDictClass):
            for k, v in value.items():
                instanceDict.__setitem__(k, v, at=at, label=label)
            instanceDict._setSelection(value._selection, at=at, label=label)

        else:
            instanceDict._setSelection(value, at=at, label=label)
    def retarget(self, target, ConfigClass=None, at=None, label="retarget"):
        """Target a new configurable and ConfigClass
        """
        if self._config._frozen:
            raise FieldValidationError(self._field, self._config,
                                       "Cannot modify a frozen Config")

        try:
            ConfigClass = self._field.validateTarget(target, ConfigClass)
        except BaseException as e:
            raise FieldValidationError(self._field, self._config, str(e))

        if at is None:
            at = getCallStack()
        object.__setattr__(self, "_target", target)
        if ConfigClass != self.ConfigClass:
            object.__setattr__(self, "_ConfigClass", ConfigClass)
            self.__initValue(at, label)

        history = self._config._history.setdefault(self._field.name, [])
        msg = "retarget(target=%s, ConfigClass=%s)" % (_typeStr(target),
                                                       _typeStr(ConfigClass))
        history.append((msg, at, label))
예제 #12
0
    def __set__(self, instance, value, at=None, label="assignment"):
        if instance._frozen:
            raise FieldValidationError(self, instance,
                                       "Cannot modify a frozen Config")

        if at is None:
            at = getCallStack()

        if value is not None:
            value = List(instance, self, value, at, label)
        else:
            history = instance._history.setdefault(self.name, [])
            history.append((value, at, label))

        instance._storage[self.name] = value
    def discard(self, value, at=None):
        """Discard a value from the selected set.
        """
        if self._config._frozen:
            raise FieldValidationError(self._field, self._config,
                                       "Cannot modify a frozen Config")

        if value not in self._dict:
            return

        if at is None:
            at = getCallStack()

        self.__history.append(
            ("removed %s from selection" % value, at, "selection"))
        self._set.discard(value)
예제 #14
0
 def __init__(self, config, field, value, at, label, setHistory=True):
     self._field = field
     self._config = config
     self._history = self._config._history.setdefault(self._field.name, [])
     self._list = []
     self.__doc__ = field.doc
     if value is not None:
         try:
             for i, x in enumerate(value):
                 self.insert(i, x, setHistory=False)
         except TypeError:
             msg = "Value %s is of incorrect type %s. Sequence type expected" % (
                 value, _typeStr(value))
             raise FieldValidationError(self._field, self._config, msg)
     if setHistory:
         self.history.append((list(self._list), at, label))
 def __getitem__(self, k, at=None, label="default"):
     try:
         value = self._dict[k]
     except KeyError:
         try:
             dtype = self.types[k]
         except Exception:
             raise FieldValidationError(
                 self._field, self._config,
                 "Unknown key %r in Registry/ConfigChoiceField" % k)
         name = _joinNamePath(self._config._name, self._field.name, k)
         if at is None:
             at = getCallStack()
             at.insert(0, dtype._source)
         value = self._dict.setdefault(
             k, dtype(__name=name, __at=at, __label=label))
     return value
    def __setattr__(self, name, value, at=None, label="assignment"):
        """Pretend to be an instance of ConfigClass.

        Attributes defined by ConfigurableInstance will shadow those defined
        in ConfigClass
        """
        if self._config._frozen:
            raise FieldValidationError(self._field, self._config,
                                       "Cannot modify a frozen Config")

        if name in self.__dict__:
            # attribute exists in the ConfigurableInstance wrapper
            object.__setattr__(self, name, value)
        else:
            if at is None:
                at = getCallStack()
            self._value.__setattr__(name, value, at=at, label=label)
    def __delattr__(self, name, at=None, label="delete"):
        """
        Pretend to be an isntance of  ConfigClass.
        Attributes defiend by ConfigurableInstance will shadow those defined
        in ConfigClass
        """
        if self._config._frozen:
            raise FieldValidationError(self._field, self._config,
                                       "Cannot modify a frozen Config")

        try:
            # attribute exists in the ConfigurableInstance wrapper
            object.__delattr__(self, name)
        except AttributeError:
            if at is None:
                at = getCallStack()
            self._value.__delattr__(name, at=at, label=label)
    def add(self, value, at=None):
        """Add a value to the selected set.
        """
        if self._config._frozen:
            raise FieldValidationError(self._field, self._config,
                                       "Cannot modify a frozen Config")

        if at is None:
            at = getCallStack()

        if value not in self._dict:
            # invoke __getitem__ to make sure it's present
            self._dict.__getitem__(value, at=at)

        self.__history.append(
            ("added %s to selection" % value, at, "selection"))
        self._set.add(value)
    def _setSelection(self, value, at=None, label="assignment"):
        if self._config._frozen:
            raise FieldValidationError(self._field, self._config,
                                       "Cannot modify a frozen Config")

        if at is None:
            at = getCallStack(1)

        if value is None:
            self._selection = None
        elif self._field.multi:
            self._selection = SelectionSet(self, value, setHistory=False)
        else:
            if value not in self._dict:
                self.__getitem__(
                    value,
                    at=at)  # just invoke __getitem__ to make sure it's present
            self._selection = value
        self._history.append((value, at, label))
예제 #20
0
    def __setitem__(self, i, x, at=None, label="setitem", setHistory=True):
        if self._config._frozen:
            raise FieldValidationError(self._field, self._config,
                                       "Cannot modify a frozen Config")
        if isinstance(i, slice):
            k, stop, step = i.indices(len(self))
            for j, xj in enumerate(x):
                xj = _autocast(xj, self._field.itemtype)
                self.validateItem(k, xj)
                x[j] = xj
                k += step
        else:
            x = _autocast(x, self._field.itemtype)
            self.validateItem(i, x)

        self._list[i] = x
        if setHistory:
            if at is None:
                at = getCallStack()
            self.history.append((list(self._list), at, label))
 def _setName(self, value):
     if self._field.multi:
         raise FieldValidationError(
             self._field, self._config,
             "Multi-selection field has no attribute 'name'")
     self._setSelection(value)
 def _setNames(self, value):
     if not self._field.multi:
         raise FieldValidationError(
             self._field, self._config,
             "Single-selection field has no attribute 'names'")
     self._setSelection(value)
 def _getName(self):
     if self._field.multi:
         raise FieldValidationError(
             self._field, self._config,
             "Multi-selection field has no attribute 'name'")
     return self._selection
 def _delNames(self):
     if not self._field.multi:
         raise FieldValidationError(
             self._field, self._config,
             "Single-selection field has no attribute 'names'")
     self._selection = None
 def _delName(self):
     if self._field.multi:
         raise FieldValidationError(
             self._field, self._config,
             "Multi-selection field has no attribute 'name'")
     self._selection = None