Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DictConfig.get() always returns None for non existing keys #509

Merged
merged 1 commit into from
Feb 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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