Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Make Example.__hash__ order-insensitive to match __eq__ (#9858)

Kyle59ce7601ec40
diff --git a/dspy/primitives/example.py b/dspy/primitives/example.py
index ce58f4af3..0fec74c03 100644
--- a/dspy/primitives/example.py
+++ b/dspy/primitives/example.py
@@ -165,7 +165,7 @@ class Example:
return isinstance(other, Example) and self._store == other._store
def __hash__(self):
- return hash(tuple(self._store.items()))
+ return hash(frozenset(self._store.items()))
def keys(self, include_dspy=False):
"""Return field names, like `dict.keys()`.
diff --git a/tests/primitives/test_example.py b/tests/primitives/test_example.py
index e100012bf..715304370 100644
--- a/tests/primitives/test_example.py
+++ b/tests/primitives/test_example.py
@@ -84,6 +84,24 @@ def test_example_hash():
assert hash(example1) == hash(example2)
+def test_example_hash_is_order_insensitive():
+ # `__eq__` compares the underlying dict (order-insensitive), so the hash
+ # contract requires `__hash__` to be order-insensitive as well.
+ example1 = Example(a=1, b=2)
+ example2 = Example(b=2, a=1)
+ assert example1 == example2
+ assert hash(example1) == hash(example2)
+
+
+def test_example_set_and_dict_lookup_after_reorder():
+ # Direct consequence of the hash contract: equal Examples constructed in
+ # different field orders must deduplicate in sets and look up in dicts.
+ example1 = Example(a=1, b=2)
+ example2 = Example(b=2, a=1)
+ assert len({example1, example2}) == 1
+ assert {example1: "v"}.get(example2) == "v"
+
+
def test_example_keys_values_items():
example = Example(a=1, b=2, dspy_hidden=3)
assert set(example.keys()) == {"a", "b"}