def validate_and_convert_to_enum( enum_type: Type[Enum], value: Any ) -> Optional[Enum]: if value is None: return None if not isinstance(value, (str, int)) and not isinstance(value, enum_type): # if type(value) not in (str, int) and not isinstance(value, enum_type): raise ValidationError( f"Value {value} ({type(value).__name__}) is not a valid input for {enum_type}" ) if isinstance(value, enum_type): return value try: if isinstance(value, (float, bool)): raise ValueError if isinstance(value, int): return enum_type(value) if isinstance(value, str): prefix = "{}.".format(enum_type.__name__) if value.startswith(prefix): value = value[len(prefix) :] return enum_type[value] assert False # pragma: no cover except (ValueError, KeyError): valid = "\n".join([f"\t{x}" for x in enum_type.__members__.keys()]) raise ValidationError( f"Invalid value '{value}', expected one of:\n{valid}" ) from None
def validate_and_convert_to_enum(enum_type: Type[Enum], value: Any) -> Enum: if not isinstance(value, (str, int)) and not isinstance(value, enum_type): raise ValidationError( f"Value $VALUE ($VALUE_TYPE) is not a valid input for {enum_type}" ) if isinstance(value, enum_type): return value try: if isinstance(value, (float, bool)): raise ValueError if isinstance(value, int): return enum_type(value) if isinstance(value, str): prefix = f"{enum_type.__name__}." if value.startswith(prefix): value = value[len(prefix) :] return enum_type[value] assert False except (ValueError, KeyError) as e: valid = ", ".join([x for x in enum_type.__members__.keys()]) raise ValidationError( f"Invalid value '$VALUE', expected one of [{valid}]" ).with_traceback(sys.exc_info()[2]) from e
def _strict_validate_type(self, value: Any) -> None: ref_type = self._metadata.ref_type if isinstance(ref_type, type) and type(value) is not ref_type: type_hint = type_str(self._metadata.type_hint) raise ValidationError( f"Value '$VALUE' of type '$VALUE_TYPE' is incompatible with type hint '{type_hint}'" )
def __init__( self, enum_type: Type[Enum], value: Optional[Union[Enum, str]] = None, key: Any = None, parent: Optional[Container] = None, is_optional: bool = True, flags: Optional[Dict[str, bool]] = None, ): if not isinstance(enum_type, type) or not issubclass(enum_type, Enum): raise ValidationError( f"EnumNode can only operate on Enum subclasses ({enum_type})" ) self.fields: Dict[str, str] = {} self.enum_type: Type[Enum] = enum_type for name, constant in enum_type.__members__.items(): self.fields[name] = constant.value super().__init__( parent=parent, value=value, metadata=Metadata( key=key, optional=is_optional, ref_type=enum_type, object_type=enum_type, flags=flags, ), )
def _validate_and_convert_impl(self, value: Any) -> str: from omegaconf import OmegaConf if OmegaConf.is_config(value) or is_primitive_container(value): raise ValidationError( "Cannot convert '$VALUE_TYPE' to string: '$VALUE'") return str(value)
def _validate_and_convert_impl(self, value: Any) -> Path: if not isinstance(value, (str, Path)): raise ValidationError( "Value '$VALUE' of type '$VALUE_TYPE' could not be converted to Path" ) return Path(value)
def validate_and_convert(self, value: Any) -> Optional[str]: from omegaconf import OmegaConf if OmegaConf.is_config(value) or is_primitive_container(value): raise ValidationError( "Cannot convert '$VALUE_TYPE' to string : '$VALUE'") return str(value) if value is not None else None
def _validate_and_convert_impl(self, value: Any) -> float: try: if type(value) in (float, str, int): return float(value) else: raise ValueError() except ValueError: raise ValidationError( "Value '$VALUE' could not be converted to Float")
def validate_and_convert(self, value: Any) -> Optional[float]: if value is None: return None try: if type(value) in (float, str, int): return float(value) else: raise ValueError() except ValueError: raise ValidationError("Value '$VALUE' could not be converted to Float")
def _validate_and_convert_impl(self, value: Any) -> int: try: if type(value) in (str, int): val = int(value) else: raise ValueError() except ValueError: raise ValidationError( "Value '$VALUE' could not be converted to Integer") return val
def _validate_and_convert_impl(self, value: Any) -> bool: if isinstance(value, bool): return value if isinstance(value, int): return value != 0 elif isinstance(value, str): try: return self._validate_and_convert_impl(int(value)) except ValueError as e: if value.lower() in ("yes", "y", "on", "true"): return True elif value.lower() in ("no", "n", "off", "false"): return False else: raise ValidationError( "Value '$VALUE' is not a valid bool (type $VALUE_TYPE)" ).with_traceback(sys.exc_info()[2]) from e else: raise ValidationError( "Value '$VALUE' is not a valid bool (type $VALUE_TYPE)")
def validate_and_convert(self, value: Any) -> Optional[int]: try: if value is None: val = None elif type(value) in (str, int): val = int(value) else: raise ValueError() except ValueError: raise ValidationError("Value '$VALUE' could not be converted to Integer") return val
def env(key: str, default: Optional[str] = None) -> Any: warnings.warn( "The `env` resolver is deprecated, see https://github.com/omry/omegaconf/issues/573" ) try: return decode_primitive(os.environ[key]) except KeyError: if default is not None: return decode_primitive(default) else: raise ValidationError(f"Environment variable '{key}' not found")
def validate_and_convert(self, value: Any) -> Any: """ Validates input and converts to canonical form :param value: input value :return: converted value ("100" may be converted to 100 for example) """ if value is None: if self._is_optional(): return None raise ValidationError("Non optional field cannot be assigned None") # Subclasses can assume that `value` is not None in `_validate_and_convert_impl()`. return self._validate_and_convert_impl(value)
def _set_value(self, value: Any) -> None: from ._utils import ValueKind, get_value_kind if isinstance(value, str) and get_value_kind(value) in ( ValueKind.INTERPOLATION, ValueKind.STR_INTERPOLATION, ValueKind.MANDATORY_MISSING, ): self._val = value else: if not self._metadata.optional and value is None: raise ValidationError("Non optional field cannot be assigned None") self._val = self.validate_and_convert(value)
def validate_and_convert(self, value: Any) -> Optional[bool]: if isinstance(value, bool): return value if isinstance(value, int): return value != 0 elif value is None: return None elif isinstance(value, str): try: return self.validate_and_convert(int(value)) except ValueError: if value.lower() in ("yes", "y", "on", "true"): return True elif value.lower() in ("no", "n", "off", "false"): return False else: raise ValidationError( "Value '{}' is not a valid bool".format(value) ) from None else: raise ValidationError( f"Value '{value}' is not a valid bool (type {type(value).__name__})" )
def validate_and_convert(self, value: Any) -> Any: """ Validates input and converts to canonical form :param value: input value :return: converted value ("100" may be converted to 100 for example) """ if value is None: if self._is_optional(): return None ref_type_str = type_str(self._metadata.ref_type) raise ValidationError( f"Incompatible value '{value}' for field of type '{ref_type_str}'" ) # Subclasses can assume that `value` is not None in `_validate_and_convert_impl()`. return self._validate_and_convert_impl(value)
def _set_value(self, value: Any, flags: Optional[Dict[str, bool]] = None) -> None: from ._utils import ValueKind, get_value_kind if self._get_flag("readonly"): raise ReadonlyConfigError("Cannot set value of read-only config node") if isinstance(value, str) and get_value_kind(value) in ( ValueKind.INTERPOLATION, ValueKind.STR_INTERPOLATION, ValueKind.MANDATORY_MISSING, ): self._val = value else: if not self._metadata.optional and value is None: raise ValidationError("Non optional field cannot be assigned None") self._val = self.validate_and_convert(value)
def _strict_validate_type(self, value: Any) -> None: if not isinstance(value, Path): raise ValidationError( "Value '$VALUE' of type '$VALUE_TYPE' is not an instance of 'pathlib.Path'" )
def _validate_and_convert_impl(self, value: Any) -> bytes: if not isinstance(value, bytes): raise ValidationError( "Value '$VALUE' of type '$VALUE_TYPE' is not of type 'bytes'") return value