From ae70a220cffb3a75375be57e5af1c2984820d174 Mon Sep 17 00:00:00 2001 From: Frederik Berlaen Date: Wed, 4 May 2022 14:47:07 +0200 Subject: [PATCH] add __eq__ and __hash__ to FuzzyNumber --- Lib/defcon/test/tools/test_fuzzyNumber.py | 17 ++++++++++++++++- Lib/defcon/tools/fuzzyNumber.py | 8 ++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Lib/defcon/test/tools/test_fuzzyNumber.py b/Lib/defcon/test/tools/test_fuzzyNumber.py index 003b66af..98e6470e 100644 --- a/Lib/defcon/test/tools/test_fuzzyNumber.py +++ b/Lib/defcon/test/tools/test_fuzzyNumber.py @@ -21,7 +21,7 @@ def test_repr(self): def test_comparison(self): fuzzyNumber1 = FuzzyNumber(value=0, threshold=1) - # self.assertEqual(fuzzyNumber1, 0) + self.assertEqual(fuzzyNumber1, 0) self.assertTrue(fuzzyNumber1 < 1) self.assertFalse(fuzzyNumber1 < -0.000001) self.assertFalse(fuzzyNumber1 < 0) @@ -53,3 +53,18 @@ def test_comparison(self): "[[-1.000000 1.000000], [0.000000 1.000000]]" ) self.assertTrue(fuzzyNumber1 > fuzzyNumber2) + + # equal + self.assertEqual(fuzzyNumber1, fuzzyNumber1) + self.assertNotEqual(fuzzyNumber1, fuzzyNumber2) + + # complex sorting + fuzzyNumber2 = FuzzyNumber(value=0.999999, threshold=1) + self.assertEqual( + repr(sorted([(fuzzyNumber1, 20), (fuzzyNumber2, 10)])), + "[([0.999999 1.000000], 10), ([0.000000 1.000000], 20)]" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/defcon/tools/fuzzyNumber.py b/Lib/defcon/tools/fuzzyNumber.py index 3b384ac8..c82ec354 100644 --- a/Lib/defcon/tools/fuzzyNumber.py +++ b/Lib/defcon/tools/fuzzyNumber.py @@ -14,3 +14,11 @@ def __lt__(self, other): else: return self.value < other.value return self.value < other + + def __eq__(self, other): + if hasattr(other, "value"): + return abs(self.value - other.value) < self.threshold + return self.value == other + + def __hash__(self): + return hash((self.value, self.threshold))