I’m having trouble with figuring out why the first of these assertions is OK and the second raises an error.
subject_list = [Subject("A"), Subject("B"), Subject("C")]
subject_set = set()
subject_set.add(Subject("A"))
subject_set.add(Subject("B"))
subject_set.add(Subject("C"))
self.assertIn(Subject("A"), subject_list)
self.assertIn(Subject("A"), subject_set)
Here is the error:
Traceback (most recent call last):
File "C:\Users\...\testSubject.py", line 34, in testIn
self.assertIn(Subject("A"), subject_set)
AssertionError: <Subject: A> not found in set([<Subject: B>, <Subject: C>, <Subject: A>])
The test for equality in the Subject class is simply self.name == other.name, and in another UnitTest I verify that Subject("A") == Subject("A") . I really can’t figure out why the subject is in the list and not in the set. Ideally I’d like the subject to be in both.
The expression
will compare
Subject("A")to each entry insubject_listusing theSubject.__eq__()method. If this method is not overwritten, it defaults to always returnFalseunless the two operands are the same object. The above expression would always returnFalseifSubjectlacked a__eq__()method, sinceSubject("A")is a new instance which cannot already be in the list.The expression
on the contrary will use
Subject.__hash__()first to find the right bucket, and useSubject.__eq__()only after this. If you did not defineSubject.__hash__()in a way compatible withSubject.__eq__(), this will fail.