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

OmegaConf.missing_keys to get a set of missing keys #719

Merged
merged 19 commits into from
Dec 17, 2021
Merged
Show file tree
Hide file tree
Changes from 13 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
18 changes: 18 additions & 0 deletions docs/source/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -782,6 +782,24 @@ and ``OmegaConf.is_list(cfg)`` is equivalent to ``isinstance(cfg, ListConfig)``.
>>> assert not OmegaConf.is_dict(l)


OmegaConf.missing_keys
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Gives a set of missing keys represented in a dotlist style.
Ohad31415 marked this conversation as resolved.
Show resolved Hide resolved
This utility function can be used at the end of creating configuration, after merging sources and so on,
to check for remaining mandatory fields and prompt a proper error message.
Ohad31415 marked this conversation as resolved.
Show resolved Hide resolved

.. doctest::

>>> missings = OmegaConf.missing_keys({
... "foo": {"bar": "???"},
... "missing": "???",
... "list": ["a", None, "???"]
... })
>>> assert missings == {'list[2]', 'foo.bar', 'missing'}

A plain dict, list or any valid input for `OmegaConf.create` is also acceptable - the function would raise a `ValueError` exception on wrong input.

Jasha10 marked this conversation as resolved.
Show resolved Hide resolved

Debugger integration
--------------------

Expand Down
1 change: 1 addition & 0 deletions news/720.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
New `OmegaConf.missing_keys` method that returns the missing keys in a config object
31 changes: 30 additions & 1 deletion omegaconf/omegaconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
Callable,
Dict,
Generator,
Iterable,
List,
Optional,
Set,
Tuple,
Type,
Union,
Expand Down Expand Up @@ -785,6 +787,34 @@ def resolve(cfg: Container) -> None:
)
omegaconf._impl._resolve(cfg)

@staticmethod
def missing_keys(cfg: Any) -> Set[str]:
"""
Returns a set of missing keys flatten in a dotlist style.
:param cfg: An `OmegaConf.Container`,
or a convertible object via `OmegaConf.create` (dict, list, ...).
:return: set of strings of the missing keys.
:raises ValueError: On input not representing a config.
"""
cfg = _ensure_container(cfg)
missings: Set[str] = set()

def gather(_cfg: Container) -> None:
itr: Iterable[Any]
if isinstance(_cfg, ListConfig):
itr = range(len(_cfg))
else:
itr = _cfg

for key in itr:
if OmegaConf.is_missing(_cfg, key):
missings.add(_cfg._get_full_key(key))
elif OmegaConf.is_config(_cfg[key]):
gather(_cfg[key])

gather(cfg)
return missings

# === private === #

@staticmethod
Expand Down Expand Up @@ -907,7 +937,6 @@ def flag_override(
names: Union[List[str], str],
values: Union[List[Optional[bool]], Optional[bool]],
) -> Generator[Node, None, None]:

if isinstance(names, str):
names = [names]
if values is None or isinstance(values, bool):
Expand Down
89 changes: 89 additions & 0 deletions tests/test_omegaconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,3 +518,92 @@ def test_resolve(cfg: Any, expected: Any) -> None:
def test_resolve_invalid_input() -> None:
with raises(ValueError):
OmegaConf.resolve("aaa") # type: ignore


@mark.parametrize(
"cfg, expected",
[
# dict:
({"a": 10, "b": {"c": "???", "d": "..."}}, {"b.c"}),
(
{
"a": "???",
"b": {
"foo": "bar",
"bar": "???",
"more": {"missing": "???", "available": "yes"},
},
Color.GREEN: {"tint": "???", "default": Color.BLUE},
},
{"a", "b.bar", "b.more.missing", "GREEN.tint"},
),
(
{"a": "a", "b": {"foo": "bar", "bar": "foo"}},
set(),
),
(
{"foo": "bar", "bar": "???", "more": {"foo": "???", "bar": "foo"}},
{"bar", "more.foo"},
),
# list:
(["???", "foo", "bar", "???", 77], {"[0]", "[3]"}),
(["", "foo", "bar"], set()),
(["foo", "bar", "???"], {"[2]"}),
(["foo", "???", ["???", "bar"]], {"[1]", "[2][0]"}),
# mixing:
(
[
"???",
"foo",
{
"a": True,
"b": "???",
"c": ["???", None],
"d": {"e": "???", "f": "fff", "g": [True, "???"]},
},
"???",
77,
],
{"[0]", "[2].b", "[2].c[0]", "[2].d.e", "[2].d.g[1]", "[3]"},
),
(
{
"list": [
0,
DictConfig({"foo": "???", "bar": None}),
"???",
["???", 3, False],
],
"x": "y",
"y": "???",
},
{"list[1].foo", "list[2]", "list[3][0]", "y"},
),
({Color.RED: ["???", {"missing": "???"}]}, {"RED[0]", "RED[1].missing"}),
# with DictConfig and ListConfig:
(
DictConfig(
{
"foo": "???",
"list": ["???", 1],
"bar": {"missing": "???", "more": "yes"},
}
),
{"foo", "list[0]", "bar.missing"},
),
(
ListConfig(
["???", "yes", "???", [0, 1, "???"], {"missing": "???", "more": ""}],
),
{"[0]", "[2]", "[3][2]", "[4].missing"},
),
],
)
def test_missing_keys(cfg: Any, expected: Any) -> None:
assert OmegaConf.missing_keys(cfg) == expected


@mark.parametrize("cfg", [float, int])
def test_missing_keys_invalid_input(cfg: Any) -> None:
with raises(ValueError):
OmegaConf.missing_keys(cfg)