Cole Bisaccia
Cole Bisaccia

Reputation: 71

When you override __eq__ in a class, do you also need to override __hash__?

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.

  1. Will this approach work for finding nodes in the structure by comparing equality?
  2. Do I also need to override __hash__?

Upvotes: 2

Views: 762

Answers (2)

Alexey Romanov
Alexey Romanov

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

shx2
shx2

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

Related Questions