Skip to content

Commit

Permalink
feat[config.py]: Add initialisation from dict
Browse files Browse the repository at this point in the history
  • Loading branch information
Artem Vasenin committed Sep 22, 2020
1 parent 8ee8ea9 commit e83cec3
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
2 changes: 1 addition & 1 deletion ntc/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .config import *
from .errors import *

__version__ = "0.1.2"
__version__ = "0.1.3"
18 changes: 13 additions & 5 deletions ntc/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class CfgNode(UserDict):

def __init__(
self,
base: CfgNode = None,
base: dict = None,
leaf_spec: Union[CfgLeaf, _CfgLeafSpec] = None,
schema_frozen: bool = False,
frozen: bool = False,
Expand Down Expand Up @@ -239,10 +239,18 @@ def _set_existing(self, key: str, value: Any) -> None:
)
super().__setitem__(key, value)

def _init_with_base(self, base: CfgNode) -> None:
setattr(self, CfgNode._LEAF_SPEC, base.leaf_spec)
self._set_attrs(base.attrs)
self.freeze_schema()
def _init_with_base(self, base: dict) -> None:
if isinstance(base, CfgNode):
setattr(self, CfgNode._LEAF_SPEC, base.leaf_spec)
self._set_attrs(base.attrs)
self.freeze_schema()
elif isinstance(base, dict):
for key, value in base.items():
if isinstance(value, dict):
value = CfgNode(value)
self[key] = value
else:
raise ValueError(f"Unknown base format {base}")


class CfgLeaf:
Expand Down
6 changes: 6 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,9 @@ def test_get():
cfg["BAR"]
assert cfg.get("BAR") is None
assert cfg.get("BAR", "foo") == "foo"


def test_init_from_dict():
cfg = CfgNode({"FOO": "bar", "BAR": {"BAZ": "foo"}})
assert cfg.FOO == "bar"
assert cfg.BAR.BAZ == "foo"

0 comments on commit e83cec3

Please sign in to comment.