Skip to content

Commit

Permalink
fix: Different hash for same dictionaries problem (#32)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
alexeykomp committed Aug 30, 2024
1 parent 31c2aa9 commit 7f3fd66
Showing 1 changed file with 3 additions and 0 deletions.
3 changes: 3 additions & 0 deletions deepmerge/extended_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 7f3fd66

Please # to comment.