Skip to content

Commit

Permalink
add __eq__ and __hash__ to FuzzyNumber
Browse files Browse the repository at this point in the history
  • Loading branch information
typemytype committed May 4, 2022
1 parent 34e78e9 commit ae70a22
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
17 changes: 16 additions & 1 deletion Lib/defcon/test/tools/test_fuzzyNumber.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()
8 changes: 8 additions & 0 deletions Lib/defcon/tools/fuzzyNumber.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

0 comments on commit ae70a22

Please sign in to comment.