From 7f3fd6627df8b6d5cab700cdfc0c7cd630323c10 Mon Sep 17 00:00:00 2001 From: Aleksei Kompaniets <90248631+alexeykomp@users.noreply.github.com> Date: Fri, 30 Aug 2024 07:17:42 +0200 Subject: [PATCH] fix: Different hash for same dictionaries problem (#32) When merging unhashable types, the hash is calculated based on `str(obj)`. The problem appears when the hash is calculated for two dictionaries like `a = {'foo': 1, 'bar': 2}` and `b = {'bar': 2, 'foo': 1}.` In this case, the calculated hashes obviously don't match, though from any other perspective, the dictionaries have no difference. --- deepmerge/extended_set.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/deepmerge/extended_set.py b/deepmerge/extended_set.py index 3efb399..de44a01 100644 --- a/deepmerge/extended_set.py +++ b/deepmerge/extended_set.py @@ -22,6 +22,9 @@ def _insert(self, element: Any) -> None: def _hash_element(self, element: Any) -> int: if getattr(element, "__hash__") is not None: return hash(element) + elif isinstance(element, dict): + sorted_keys = sorted(element.keys()) + return hash(",".join([f"{key}:{element[key]}" for key in sorted_keys])) return hash(str(element)) def __contains__(self, obj: Any) -> bool: