Make42 Make42 - 1 month ago 5
Python Question

Implementing __eq__ via __hash__?

Reading How to implement a good __hash__ function in python - can I not write eq as

def __eq__(self, other):
return isinstance(other, self.__class__) and hash(other) == hash(self)

def __ne__(self, other):
return not self.__eq__(other)

def __hash__(self):
return hash((self.firstfield, self.secondfield, totuple(self.thirdfield)))


? Of course I am going to implement
__hash__(self)
as well. I have rather clearly defined class members. I am going to turn them all into tuples and make a total tuple out of those and hash that.

Answer

Generally speaking, a hash function will have collisions. If you define equality in terms of a hash, you're running the risk of entirely dissimilar items comparing as equal, simply because they ended up with the same hash code. The only way to avoid this would be if your class only had a small, fixed number of possible instances, and you somehow ensured that each one of those had a distinct hash. If your class is simple enough for that to be practical, then it is almost certainly simple enough for you to just compare instance variables to determine equality directly. Your __hash__() implementation would have to examine all the instance variables anyway, in order to calculate a meaningful hash.

Comments