]> granicus.if.org Git - python/commitdiff
Classes that override __eq__ also need to define __hash__.
authorRaymond Hettinger <python@rcn.com>
Mon, 5 Apr 2010 18:53:43 +0000 (18:53 +0000)
committerRaymond Hettinger <python@rcn.com>
Mon, 5 Apr 2010 18:53:43 +0000 (18:53 +0000)
Lib/functools.py
Lib/test/test_functools.py

index ad1cccc77f0970d85fcbfc8875ba7686a56a6b97..539dc90ecd8fcb770efff3c6984e704523ef8b56 100644 (file)
@@ -93,4 +93,6 @@ def cmp_to_key(mycmp):
             return mycmp(self.obj, other.obj) >= 0
         def __ne__(self, other):
             return mycmp(self.obj, other.obj) != 0
+        def __hash__(self):
+            raise TypeError('hash not implemented')
     return K
index 1629f7ce4e8104dff9c5cb3a7cc143041d225bda..05e19b1399fdd65bb215592a0a4a94706c929657 100644 (file)
@@ -345,6 +345,13 @@ class TestCmpToKey(unittest.TestCase):
         self.assertEqual(sorted(range(5), key=functools.cmp_to_key(mycmp)),
                          [4, 3, 2, 1, 0])
 
+    def test_hash(self):
+        def mycmp(x, y):
+            return y - x
+        key = functools.cmp_to_key(mycmp)
+        k = key(10)
+        self.assertRaises(TypeError, hash(k))
+
 class TestTotalOrdering(unittest.TestCase):
 
     def test_total_ordering_lt(self):