Skip to content

Commit

Permalink
fixes merge with non-str keys
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhiyuanChen authored Jul 14, 2023
1 parent f01482c commit 5dbb26a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
5 changes: 5 additions & 0 deletions chanfig/flat_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,6 +505,11 @@ def merge(self, *args, **kwargs) -> FlatDict:
{'a': 1, 'b': 'b', 'c': 3, 'd': 4}
>>> FlatDict(a=1, b=1, c=1).union(FlatDict(b='b', c='c', d='d')).dict() # alias
{'a': 1, 'b': 'b', 'c': 'c', 'd': 'd'}
>>> d = FlatDict()
>>> d.merge({1: 1, 2: 2, 3:3}).dict()
{1: 1, 2: 2, 3: 3}
>>> d.merge(d.clone()).dict()
{1: 1, 2: 2, 3: 3}
"""

@wraps(self.merge)
Expand Down
11 changes: 8 additions & 3 deletions chanfig/nested_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -581,16 +581,19 @@ def merge(self, *args, **kwargs) -> NestedDict:
>>> d.c = {"b": {"d": 3, "e": {"f": 4}}}
>>> d.merge(n).dict()
{'c': {'b': {'d': 3, 'e': {'f': 4}}, 'd': {'f': 5}}, 'b': {'c': 3, 'd': 5}, 'd': 0}
>>> d = NestedDict()
>>> d.merge(a={1:1}, b={2:2},c={3:3}).dict()
{'a': {1: 1}, 'b': {2: 2}, 'c': {3: 3}}
>>> d.merge(d.clone()).dict()
{'a': {1: 1}, 'b': {2: 2}, 'c': {3: 3}}
"""

if not args and not kwargs:
return self

@wraps(self.merge)
def merge(this: NestedDict, that: Iterable) -> Mapping:
if isinstance(that, NestedDict):
that = that.all_items()
elif isinstance(that, Mapping):
if isinstance(that, Mapping):
that = that.items()
for key, value in that:
if key in this and isinstance(this[key], Mapping):
Expand All @@ -600,6 +603,8 @@ def merge(this: NestedDict, that: Iterable) -> Mapping:
this.set(key, value, convert_mapping=True)
else:
this[key] = value
elif key in dir(this) and isinstance(getattr(this.__class__, key), property):
getattr(this, key).merge(value)
elif isinstance(this, NestedDict):
this.set(key, value, convert_mapping=True)
else:
Expand Down

0 comments on commit 5dbb26a

Please sign in to comment.