From e1d665a90e4a20a60c0c9904417160ea3c7660b7 Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Mon, 5 Apr 2010 18:53:43 +0000 Subject: Classes that override __eq__ also need to define __hash__. --- Lib/functools.py | 2 ++ Lib/test/test_functools.py | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/Lib/functools.py b/Lib/functools.py index ad1cccc..539dc90 100644 --- a/Lib/functools.py +++ b/Lib/functools.py @@ -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 diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py index 1629f7c..05e19b1 100644 --- a/Lib/test/test_functools.py +++ b/Lib/test/test_functools.py @@ -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): -- cgit v0.12