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 10 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 enables to get a config's set of missing keys represented in a dotlist style.
Ohad31415 marked this conversation as resolved.
Show resolved Hide resolved
35 changes: 34 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,38 @@ 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.
"""
if not isinstance(cfg, Container):
try:
cfg = OmegaConf.create(cfg)
except ValidationError:
raise ValueError(f"Could not create a config out of {cfg}")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that it would be appropriate to use the _ensure_container function here.

Suggested change
if not isinstance(cfg, Container):
try:
cfg = OmegaConf.create(cfg)
except ValidationError:
raise ValueError(f"Could not create a config out of {cfg}")
cfg = _ensure_container(cfg)

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. once you do, you can also change your tests to take plain dict/list instead of a Container to simplfy.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@omry The tests contain inputs of all types: ListConfig, DictConfig, plain list, dict. I think it doesn't hurt having it so, but if you think it's better with only plain lists/dicts I'll change it 😃

Copy link
Owner

@omry omry Jun 9, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's test everything with plain dict and list, but keep a single test for DictConfig and a single test for ListConfig (just for the top level element).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👌 I've simplified it adding two tests at the end one with DictConfig and one with ListConfig.

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 +941,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
78 changes: 78 additions & 0 deletions tests/test_omegaconf.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,3 +518,81 @@ 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:
(DictConfig({"a": 10, "b": {"c": "???", "d": "..."}}), {"b.c"}),
(
DictConfig(
{
"a": "???",
"b": {
"foo": "bar",
"bar": "???",
"more": {"missing": "???", "available": "yes"},
},
Color.GREEN: {"tint": "???", "default": Color.BLUE},
}
),
{"a", "b.bar", "b.more.missing", "GREEN.tint"},
),
(
DictConfig({"a": "a", "b": {"foo": "bar", "bar": "foo"}}),
set(),
),
(
{"foo": "bar", "bar": "???", "more": {"foo": "???", "bar": "foo"}},
{"bar", "more.foo"},
),
# list:
(ListConfig(["???", "foo", "bar", "???", 77]), {"[0]", "[3]"}),
(ListConfig(["", "foo", "bar"]), set()),
(["foo", "bar", "???"], {"[2]"}),
(["foo", "???", ["???", "bar"]], {"[1]", "[2][0]"}),
# mixing:
(
ListConfig(
[
"???",
"foo",
DictConfig(
{
"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"}),
],
)
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)