Skip to content

Commit

Permalink
fix flatten sep
Browse files Browse the repository at this point in the history
  • Loading branch information
narumiruna committed Nov 9, 2024
1 parent 4eefce0 commit 051f0a9
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/mlconfig/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def flatten(data: dict[str, Any], prefix: str | None = None, sep: str = ".") ->
key = prefix + sep + key

if isinstance(value, dict):
d.update(flatten(value, prefix=key))
d.update(flatten(value, prefix=key, sep=sep))
continue

d[key] = value
Expand Down
38 changes: 38 additions & 0 deletions tests/test_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,3 +90,41 @@ def test_getcls_key_not_found(conf):
conf_invalid["a"][_key] = "NonExistentKey" # Key not in registry
with pytest.raises(ValueError, match="key NonExistentKey not found in registry"):
getcls(conf_invalid["a"])


def test_register_duplicate():
with pytest.raises(ValueError, match="duplicate name Point found"):
@register(name="Point")
class PointDuplicate:
def __init__(self, x, y):
self.x = x
self.y = y

def test_instantiate_with_kwargs(conf, obj):
a = instantiate(conf.a, y=10)
assert a.y == 10
assert a.x == obj["x1"]

def test_instantiate_with_args(conf, obj):
conf_with_args = {"name": "Point"}
a = instantiate(conf_with_args, 5, 6)
assert a.x == 5
assert a.y == 6

def test_flatten_with_empty_dict():
assert flatten({}) == {}

def test_flatten_with_nested_dict():
nested_dict = {"a": {"b": {"c": "d"}}}
expected = {"a.b.c": "d"}
assert flatten(nested_dict) == expected

def test_flatten_with_prefix():
nested_dict = {"a": {"b": "c"}}
expected = {"prefix.a.b": "c"}
assert flatten(nested_dict, prefix="prefix") == expected

def test_flatten_with_custom_separator():
nested_dict = {"a": {"b": "c"}}
expected = {"a/b": "c"}
assert flatten(nested_dict, sep="/") == expected

0 comments on commit 051f0a9

Please sign in to comment.