Skip to content

Commit

Permalink
imp(node.py): Change static_init() to return cfg rather than modify i…
Browse files Browse the repository at this point in the history
…n-place

BREAKING CHANGE: cfg.static_init() now returns the initialised config
rather than initialising in-place.
  • Loading branch information
Rizhiy committed May 31, 2023
1 parent 4e64a46 commit 1f8345f
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 9 deletions.
14 changes: 8 additions & 6 deletions ntc/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ def _update_module(self, key: str, value) -> None:
import_str, cls_name, args, kwargs = value.save_strs()
lines.append(f"{import_str}\n")
lines.append(f"{key} = {value.create_eval_str(cls_name, args, kwargs)}\n")
elif isinstance(value, list) and all([type(v) in valid_types for v in value]):
elif isinstance(value, list) and all(type(v) in valid_types for v in value):
lines.append(f"{key} = {value!r}\n")
else:
message = f"Config was modified with unsavable value: {value!r}"
Expand All @@ -455,12 +455,14 @@ def _set_key_for_child(self, child: Union[CfgNode, CfgLeaf], key: str) -> None:
child.key = key
child.parent = self

def static_init(self):
def static_init(self) -> CfgNode:
"""Default initialisation when config is used as is, instead of using load()"""
self.freeze_schema()
self.transform()
self.validate()
self.run_hooks()
cfg = self.clone()
cfg.freeze_schema()
cfg.transform()
cfg.validate()
cfg.run_hooks()
return cfg


def _check_circular_path(new_node: CfgNode, key: str, parent_ids: list[int] = None):
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ test = [
"types-pyyaml",
]
dev = [
"nt-dev>=0.34",
"ntc[test]",
]

[tool.flit.sdist]
Expand Down
4 changes: 2 additions & 2 deletions tests/test_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,14 +238,14 @@ def test_static_init():
def change_foo(cfg):
cfg.FOO = "baz"

def change_value(cfg):
def change_value(_):
nonlocal VALUE
VALUE = 2

cfg.add_transform(change_foo)
cfg.add_hook(change_value)

cfg.static_init()
cfg = cfg.static_init()
assert cfg.schema_frozen
assert cfg.FOO == "baz"
assert VALUE == 2
Expand Down

0 comments on commit 1f8345f

Please sign in to comment.