From 19d3a9bcb1bc2228113079c1d725b4f4b84f104a Mon Sep 17 00:00:00 2001 From: Jasha <8935917+Jasha10@users.noreply.github.com> Date: Tue, 9 Feb 2021 14:42:03 -0600 Subject: [PATCH] api change: dictconfig.get("missing") returns None --- news/527.api_change | 1 + omegaconf/dictconfig.py | 8 ++++---- tests/test_omegaconf.py | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) create mode 100644 news/527.api_change diff --git a/news/527.api_change b/news/527.api_change new file mode 100644 index 000000000..d65f4db8c --- /dev/null +++ b/news/527.api_change @@ -0,0 +1 @@ +DictConfig get access, e.g. `cfg.get("foo")`, now returns `None` if the key "foo" does not exist diff --git a/omegaconf/dictconfig.py b/omegaconf/dictconfig.py index b08629efe..4484ef218 100644 --- a/omegaconf/dictconfig.py +++ b/omegaconf/dictconfig.py @@ -404,12 +404,12 @@ def __delitem__(self, key: DictKeyType) -> None: del self.__dict__["_content"][key] - def get(self, key: DictKeyType, default_value: Any = DEFAULT_VALUE_MARKER) -> Any: + def get(self, key: DictKeyType, default_value: Any = None) -> Any: + """Return the value for `key` if `key` is in the dictionary, else + `default_value` (defaulting to `None`).""" try: return self._get_impl(key=key, default_value=default_value) - except ConfigAttributeError: - return None - except Exception as e: + except KeyValidationError as e: self._format_and_raise(key=key, value=None, cause=e) def _get_impl(self, key: DictKeyType, default_value: Any) -> Any: diff --git a/tests/test_omegaconf.py b/tests/test_omegaconf.py index 9f0a20d0e..a7997beb4 100644 --- a/tests/test_omegaconf.py +++ b/tests/test_omegaconf.py @@ -95,7 +95,7 @@ def test_is_missing( ) -> None: cfg = OmegaConf.create(cfg) with expectation: - cfg.get(key) + cfg[key] assert OmegaConf.is_missing(cfg, key) == expected_is_missing OmegaConf.set_struct(cfg, True)