Beispiel #1
0
    def __setitem__(self, key: str, value: Any) -> None:
        """
        Override for dictionary's ``setitem`` method. This method make sure that all values are of
        Param's type only.

        :param key: A key which needs to be inserted or updated in the dict
        :type key: str
        :param value: A value which needs to be set against the key. It could be of any
            type but will be converted and stored as a Param object eventually.
        :type value: Any
        """
        if isinstance(value, Param):
            param = value
        elif key in self.__dict:
            param = self.__dict[key]
            try:
                param.resolve(value=value,
                              suppress_exception=self.suppress_exception)
            except ParamValidationError as ve:
                raise ParamValidationError(
                    f'Invalid input for param {key}: {ve}') from None
        else:
            # if the key isn't there already and if the value isn't of Param type create a new Param object
            param = Param(value)

        self.__dict[key] = param
Beispiel #2
0
    def resolve(self,
                value: Any = NOTSET,
                suppress_exception: bool = False) -> Any:
        """
        Runs the validations and returns the Param's final value.
        May raise ValueError on failed validations, or TypeError
        if no value is passed and no value already exists.
        We first check that value is json-serializable; if not, warn.
        In future release we will require the value to be json-serializable.

        :param value: The value to be updated for the Param
        :param suppress_exception: To raise an exception or not when the validations fails.
            If true and validations fails, the return value would be None.
        """
        import jsonschema
        from jsonschema import FormatChecker
        from jsonschema.exceptions import ValidationError

        try:
            json.dumps(value)
        except Exception:
            warnings.warn(
                "The use of non-json-serializable params is deprecated and will be removed in "
                "a future release",
                DeprecationWarning,
            )
        final_val = value if value is not NOTSET else self.value
        if isinstance(final_val, ArgNotSet):
            if suppress_exception:
                return None
            raise ParamValidationError(
                "No value passed and Param has no default value")
        try:
            jsonschema.validate(final_val,
                                self.schema,
                                format_checker=FormatChecker())
        except ValidationError as err:
            if suppress_exception:
                return None
            raise ParamValidationError(err) from None
        self.value = final_val
        return final_val
Beispiel #3
0
    def validate(self) -> Dict[str, Any]:
        """Validates & returns all the Params object stored in the dictionary"""
        resolved_dict = {}
        try:
            for k, v in self.items():
                resolved_dict[k] = v.resolve(
                    suppress_exception=self.suppress_exception)
        except ParamValidationError as ve:
            raise ParamValidationError(
                f'Invalid input for param {k}: {ve}') from None

        return resolved_dict