How to use the omegaconf.errors.MissingMandatoryValue function in omegaconf

To help you get started, we’ve selected a few omegaconf examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github omry / omegaconf / tests / test_basic_ops_list.py View on Github external
        (ListConfig(content="???"), 0, MissingMandatoryValue),
    ],
)
def test_get(lst: Any, idx: Any, expected: Any) -> None:
    if isinstance(expected, type):
        with pytest.raises(expected):
            lst.get(idx)
    else:
        lst.__getitem__(idx) == expected
github omry / omegaconf / tests / test_basic_ops_list.py View on Github external
def test_iterate_list_with_missing() -> None:
    c = OmegaConf.create([1, "???"])
    itr = iter(c)
    assert 1 == next(itr)
    with pytest.raises(MissingMandatoryValue):
        next(itr)
github omry / omegaconf / tests / test_errors.py View on Github external
Expected(
            create=lambda: ListConfig(content=None),
            op=lambda cfg: cfg._get_node(20),
            exception_type=TypeError,
            msg="Cannot get_node from a ListConfig object representing None",
            key=20,
            full_key="[20]",
            ref_type=Optional[List[Any]],
        ),
        id="list:get_node_none",
    ),
    pytest.param(
        Expected(
            create=lambda: ListConfig(content="???"),
            op=lambda cfg: cfg._get_node(20),
            exception_type=MissingMandatoryValue,
            msg="Cannot get_node from a missing ListConfig",
            key=20,
            full_key="[20]",
        ),
        id="list:get_node_missing",
    ),
    # list:create
    pytest.param(
        Expected(
            create=lambda: None,
            op=lambda cfg: ListConfig(is_optional=False, content=None),
            exception_type=ValidationError,
            object_type=None,
            msg="Non optional ListConfig cannot be constructed from None",
            object_type_str=None,
            ref_type_str=None,
github omry / omegaconf / omegaconf / listconfig.py View on Github external
def insert(self, index: int, item: Any) -> None:
        from omegaconf.omegaconf import OmegaConf, _maybe_wrap

        try:
            if self._get_flag("readonly"):
                raise ReadonlyConfigError("Cannot insert into a read-only ListConfig")
            if self._is_none():
                raise TypeError(
                    "Cannot insert into ListConfig object representing None"
                )
            if self._is_missing():
                raise MissingMandatoryValue("Cannot insert into missing ListConfig")

            try:
                assert isinstance(self.__dict__["_content"], list)
                # insert place holder
                self.__dict__["_content"].insert(index, None)
                node = _maybe_wrap(
                    ref_type=self.__dict__["_metadata"].element_type,
                    key=index,
                    value=item,
                    is_optional=OmegaConf.is_optional(item),
                    parent=self,
                )
                self._validate_set(key=index, value=node)
                self._set_at_index(index, node)
                self._update_keys()
            except Exception:
github omry / omegaconf / omegaconf / basecontainer.py View on Github external
return default_value

        resolved = self._resolve_interpolation(
            key=key,
            value=value,
            throw_on_missing=not has_default,
            throw_on_resolution_failure=not has_default,
        )
        if resolved is None and has_default:
            return default_value

        if is_mandatory_missing(resolved):
            if has_default:
                return default_value
            else:
                raise MissingMandatoryValue("Missing mandatory value: $FULL_KEY")

        return _get_value(resolved)
github omry / omegaconf / omegaconf / basecontainer.py View on Github external
def _is_missing(self) -> bool:
        try:
            self._dereference_node(throw_on_missing=True)
            return False
        except MissingMandatoryValue:
            ret = True

        assert isinstance(ret, bool)
        return ret
github omry / omegaconf / omegaconf / listconfig.py View on Github external
def _iter_ex(self, resolve: bool) -> Iterator[Any]:
        try:
            if self._is_none():
                raise TypeError("Cannot iterate a ListConfig object representing None")
            if self._is_missing():
                raise MissingMandatoryValue("Cannot iterate a missing ListConfig")

            class MyItems(Iterator[Any]):
                def __init__(self, lst: ListConfig) -> None:
                    self.lst = lst
                    self.index = 0

                def __next__(self) -> Any:
                    if self.index == len(self.lst):
                        raise StopIteration()
                    if resolve:
                        v = self.lst[self.index]
                    else:
                        v = self.lst.__dict__["_content"][self.index]
                        if v is not None:
                            v = _get_value(v)
                    self.index = self.index + 1
github omry / omegaconf / omegaconf / listconfig.py View on Github external
def _get_node(
        self,
        key: Union[int, slice],
        validate_access: bool = True,
        disable_warning: bool = False,
    ) -> Optional[Node]:
        try:
            if self._is_none():
                raise TypeError(
                    "Cannot get_node from a ListConfig object representing None"
                )
            if self._is_missing():
                raise MissingMandatoryValue("Cannot get_node from a missing ListConfig")
            assert isinstance(self.__dict__["_content"], list)
            if validate_access:
                self._validate_get(key)
            return self.__dict__["_content"][key]  # type: ignore
        except (IndexError, TypeError, MissingMandatoryValue, KeyValidationError) as e:
            if validate_access:
                self._format_and_raise(key=key, value=None, cause=e)
                assert False
            else:
                return None
github omry / omegaconf / omegaconf / listconfig.py View on Github external
def __getitem__(self, index: Union[int, slice]) -> Any:
        try:
            if self._is_missing():
                raise MissingMandatoryValue("ListConfig is missing")
            self._validate_get(index, None)
            if self._is_none():
                raise TypeError(
                    "ListConfig object representing None is not subscriptable"
                )

            assert isinstance(self.__dict__["_content"], list)
            if isinstance(index, slice):
                result = []
                start, stop, step = self._correct_index_params(index)
                for slice_idx in itertools.islice(
                    range(0, len(self)), start, stop, step
                ):
                    val = self._resolve_with_default(
                        key=slice_idx, value=self.__dict__["_content"][slice_idx]
                    )