Skip to content

Commit

Permalink
DictConfig.get() always returns None for non existing keys
Browse files Browse the repository at this point in the history
  • Loading branch information
omry committed Feb 3, 2021
1 parent bc8a406 commit d53960c
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 3 deletions.
1 change: 1 addition & 0 deletions news/425.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DictConfig.get() in struct mode return None like standard Dict for non-existing keys
2 changes: 2 additions & 0 deletions omegaconf/dictconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,8 @@ def __delitem__(self, key: DictKeyType) -> None:
def get(self, key: DictKeyType, default_value: Any = DEFAULT_VALUE_MARKER) -> Any:
try:
return self._get_impl(key=key, default_value=default_value)
except ConfigAttributeError:
return None
except Exception as e:
self._format_and_raise(key=key, value=None, cause=e)

Expand Down
11 changes: 8 additions & 3 deletions tests/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def test_struct_set_on_dict() -> None:


def test_struct_set_on_nested_dict() -> None:
c = OmegaConf.create(dict(a=dict(b=10)))
c = OmegaConf.create({"a": {"b": 10}})
OmegaConf.set_struct(c, True)
with pytest.raises(AttributeError):
# noinspection PyStatementEffect
Expand All @@ -37,7 +37,7 @@ def test_struct_set_on_nested_dict() -> None:


def test_merge_dotlist_into_struct() -> None:
c = OmegaConf.create(dict(a=dict(b=10)))
c = OmegaConf.create({"a": {"b": 10}})
OmegaConf.set_struct(c, True)
with pytest.raises(AttributeError, match=re.escape("foo")):
c.merge_with_dotlist(["foo=1"])
Expand All @@ -55,6 +55,11 @@ def test_merge_config_with_struct(


def test_struct_contain_missing() -> None:
c = OmegaConf.create(dict())
c = OmegaConf.create()
OmegaConf.set_struct(c, True)
assert "foo" not in c


@pytest.mark.parametrize("cfg", [{}, OmegaConf.create({}, flags={"struct": True})])
def test_struct_dict_get(cfg: Any) -> None:
assert cfg.get("z") is None

0 comments on commit d53960c

Please sign in to comment.