From 5dbb26a01e54baace712b33f446ad187be723739 Mon Sep 17 00:00:00 2001 From: Zhiyuan Chen Date: Fri, 14 Jul 2023 18:18:17 +0800 Subject: [PATCH] fixes merge with non-str keys --- chanfig/flat_dict.py | 5 +++++ chanfig/nested_dict.py | 11 ++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/chanfig/flat_dict.py b/chanfig/flat_dict.py index e62606e2..f99277e0 100644 --- a/chanfig/flat_dict.py +++ b/chanfig/flat_dict.py @@ -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) diff --git a/chanfig/nested_dict.py b/chanfig/nested_dict.py index 05620349..20f6f630 100644 --- a/chanfig/nested_dict.py +++ b/chanfig/nested_dict.py @@ -581,6 +581,11 @@ 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: @@ -588,9 +593,7 @@ def merge(self, *args, **kwargs) -> NestedDict: @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): @@ -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: