Skip to content

Commit

Permalink
Merge branch 'feat/required-field' into 'master'
Browse files Browse the repository at this point in the history
feat: required config leaf

See merge request utilities/config!3
  • Loading branch information
Vladimir Mikhaylov committed Sep 14, 2020
2 parents aba0784 + a3ecea0 commit 0dd2d1b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
21 changes: 15 additions & 6 deletions nt_config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@ def _set_existing_attr(self, key: str, value: Any) -> None:
cur_attr = super().__getattribute__(key)
value_type = type(value)
if isinstance(cur_attr, CfgLeaf):
if cur_attr.type_ != value_type:
raise TypeError(f"Value of type {cur_attr.type_} expected, but {value_type} found.")
cur_attr.value = value
else:
if not isinstance(cur_attr, value_type):
Expand All @@ -56,8 +54,19 @@ def _set_existing_attr(self, key: str, value: Any) -> None:

class CfgLeaf:
def __init__(self, value: Any, type_: Type, required: bool = False):
if value is not None and not isinstance(value, type_):
raise TypeError(f"value {value} is not of {type_} type.")
self.value = value
self.type_ = type_
self._required = required # TODO (vemikhaylov): the attribute is not currently used (should be used or removed)
self._required = required

self.value = value

@property
def value(self) -> Any:
return self._value

@value.setter
def value(self, val) -> None:
if val is not None and not isinstance(val, self.type_):
raise TypeError(f"Value of type {self.type_} expected, but {type(self.type_)} found.")
if val is None and self._required:
raise ValueError("Required config leaf cannot be None")
self._value = val
15 changes: 15 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,3 +79,18 @@ def test_str():

expected_str = "BAR:\n BAZ: baz\nFOO: 32\n"
assert str(cfg) == expected_str


def test_required():
cfg = CfgNode()

with pytest.raises(ValueError):
cfg.FOO = CfgLeaf(None, int, required=True)

cfg.FOO = CfgLeaf(32, int, required=True)
assert cfg.FOO == 32
with pytest.raises(ValueError):
cfg.FOO = None

cfg.FOO = 42
assert cfg.FOO == 42

0 comments on commit 0dd2d1b

Please sign in to comment.