I am trying to implement a standard equality operator in Python 3.3, following code samples from other questions. I'm getting an assertion error, but I can't figure out what's broken. What did I miss here?
class RollResult:
def __init__(self, points, unscored_dice):
self.points = points
self.unscored_dice = unscored_dice
def __eq__(self, other):
return (self.points == other.points and self.unscored_dice == other.unscored_dice)
And here's the test. Many other tests are passing, so the basic setup is right. This is my first test of the class and I've never tried unit testing equality overloads before, so it may be the fault of the test as well.
class TestRollResultClass(unittest.TestCase):
def test_rollresult_equality_overload_does_not_test_for_same_object(self):
copy1 = RollResult(350,2)
copy2 = RollResult(350,2)
self.assertNotEqual(copy1,copy2)
Result:
AssertionError: <greed.RollResult object at 0x7fbc21c1b650> == <greed.RollResult object at 0x7fbc21c1b650>
other
of__eq__
might not be aRollResult
instance, in which case you should returnFalse
and not raise anAttributeError
(people expect to be able to use==
between any objects, except for really strange cases which should be well documented). I suggest you to insert the code in atry: ... except AttributeError: return False
.isinstance
or doing things liketype(something) is SomeType
etc. Using Duck-typing is encouraged. Duck-typing means: you assume the object provide a certain interface, and use it. If it fails (like in this case, with anAttributeError
) you either fail the operation (possibly raising a different exception, or sometimes letting the exception through), or you continue assuming a different interface. In this case the__eq__
should first assume a "compatible interface", and otherwise fail returningFalse
.other
isn't aRollResult
, you should returnNotImplemented
. This is generally true even if you don't expect other objects to implement a meaningful equality comparison withRollResult
objects.