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

implemented and tested __contains__ (key in cfg) #49

Merged
merged 1 commit into from
Oct 26, 2019
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
19 changes: 17 additions & 2 deletions omegaconf/dictconfig.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from .config import Config
from .errors import ReadonlyConfigError, MissingMandatoryValue
from .nodes import BaseNode, UntypedNode
from .errors import ReadonlyConfigError
import copy


class DictConfig(Config):
Expand Down Expand Up @@ -98,6 +97,22 @@ def pop(self, key, default=__marker):
def keys(self):
return self.content.keys()

def __contains__(self, key):
"""
A key is contained in a DictConfig if there is an associated value and it is not a mandatory missing value ('???').
:param key:
:return:
"""
node = self.get_node(key)
if node is None:
return False
else:
try:
self._resolve_with_default(key, node, None)
return True
except (MissingMandatoryValue, KeyError):
return False

def __iter__(self):
return iter(self.keys())

Expand Down
22 changes: 13 additions & 9 deletions tests/test_basic_ops_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,15 +207,19 @@ def test_dict_pop():
c.pop('not_found')


def test_in_dict():
c = OmegaConf.create(dict(
a=1,
b=2,
c={}))
assert 'a' in c
assert 'b' in c
assert 'c' in c
assert 'd' not in c
@pytest.mark.parametrize("conf,key,expected", [
({"a": 1, "b": {}}, "a", True),
({"a": 1, "b": {}}, "b", True),
({"a": 1, "b": {}}, "c", False),
({"a": 1, "b": "${a}"}, "b", True),
({"a": 1, "b": "???"}, "b", False),
({"a": 1, "b": "???", "c": "${b}"}, "c", False),
({"a": 1, "b": "${not_found}"}, "b", False),
])
def test_in_dict(conf, key, expected):
conf = OmegaConf.create(conf)
ret = key in conf
assert ret == expected


def test_get_root():
Expand Down