Reputation: 71
I'm making a node class in Python 3 which I will be storing in a min-ordered multi-tree structure. I overrode the __eq__
method which tests for equality by comparing two unique integer instance variables.
__hash__
?Upvotes: 2
Views: 762
Reputation: 170745
I'm making a node class in Python 3 which I will be storing in a min-ordered multi-tree structure
If it's the only use, and they are only used internally so user code isn't ever supposed to see a Node
, and your code doesn't store them in dicts or sets, or call any functions which do, maybe you can get away without overriding __hash__
.
But those are very strong restrictions, which can't really be enforced. And there's no benefit to not overriding __hash__
to be consistent with __eq__
. So you still should do it.
Upvotes: 1
Reputation: 64318
Yes, you have to override __hash__
.
The general rule is: if two instances are equal (wrt to __eq__
, i.e. a==b
is True), then they must have the same hash. Otherwise, all sorts of things can misbehave.
Also, it sounds to me __eq__
is not enough for minimum. At the very least, you'd need to define __lt__
.
Upvotes: 3