Skip to content

Commit 2eabfa7

Browse files
Copilotnstarman
andauthored
Optimize mapping equality checks and add reverse comparison tests
Agent-Logs-Url: https://github.com/GalacticDynamics/xmmutablemap/sessions/f39253f1-d8ea-46eb-8a8e-f004866a473d Co-authored-by: nstarman <8949649+nstarman@users.noreply.github.com>
1 parent 63e43a0 commit 2eabfa7

2 files changed

Lines changed: 13 additions & 1 deletion

File tree

src/xmmutablemap/_core.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,12 @@ def __eq__(self, other: object) -> bool:
9494
if isinstance(other, ImmutableMap):
9595
return self._data == other._data
9696
if isinstance(other, Mapping):
97-
return self._data == dict(other.items())
97+
if len(self._data) != len(other):
98+
return False
99+
sentinel = object()
100+
return all(
101+
self._data.get(key, sentinel) == value for key, value in other.items()
102+
)
98103
return NotImplemented
99104

100105
# ===========================================

tests/test_immutablemap.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,16 @@ def test_hash(self, d: ImmutableMap[str, Any]) -> None:
6767
def test_eq_with_other_mappings(self) -> None:
6868
"""Test mapping interoperability for `__eq__`."""
6969
d = ImmutableMap(a=1, b=2)
70+
other_dict = {"a": 1, "b": 2}
71+
other_ordered_dict = OrderedDict([("a", 1), ("b", 2)])
72+
other_proxy = MappingProxyType({"a": 1, "b": 2})
73+
7074
assert d == {"a": 1, "b": 2}
7175
assert d == OrderedDict([("a", 1), ("b", 2)])
7276
assert d == MappingProxyType({"a": 1, "b": 2})
77+
assert other_dict == d
78+
assert other_ordered_dict == d
79+
assert other_proxy == d
7380

7481
def test_eq_and_hash_ignore_insertion_order(self) -> None:
7582
"""Test equality/hash contract for same items in different orders."""

0 commit comments

Comments
 (0)