Jim Newton
Jim Newton

Reputation: 652

python __eq__ and __hash__ functions

When defining a __hash__ function in python, do I need to worry about some other class's __hash__ function returning the same value? I.e., if two different objects of different classes both hash to the same value, is that a problem I need to explicitly consider in my __hash__ function?

In particular I have a class for which I enforce that it only be instantiated once. I have defined the __eq__ and __hash__ functions like this. Is this OK?

    def __eq__(self, that):
        return type(self) is type(that)

    def __hash__(self):
        return hash(0)

Upvotes: 3

Views: 2642

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19414

The __eq__ documentation states:

By default, object implements __eq__() by using is, returning NotImplemented in the case of a false comparison: True if x is y else NotImplemented.

So in your singleton class case, the default behavior is fine - only references to the same single instance will be deemed equal.

The __hash__ documentation states:

The only required property is that objects which compare equal have the same hash value.

Because you're dealing with a single instance, that can only equal itself, it is guaranteed that its own hash value will equal itself. So again, the default is fine for your case.

To seal the deal:

If a class does not define an __eq__() method it should not define a __hash__() operation either; if it defines __eq__() but not __hash__(), its instances will not be usable as items in hashable collections.

and:

User-defined classes have __eq__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns an appropriate value such that x == y implies both that x is y and hash(x) == hash(y).

All comes to show that for your use-case, there is no need to implement either.

Upvotes: 5

Related Questions