0

I have the following problem which is best described by the following example:

class TestHasher:
    def __hash__(self):
         # return the hash of the name of the class of this instance
         # which is "TstHasher"
        return hash(self.__class__.__name__)

th = TestHasher()
print(hash(th))
print(hash("TestHasher"))
 # prints the same result as hash(th)
 # -> the hash value for th and "TestHasher" are the same, everything worked so far
d = {"TestHasher": "it worked!"}
print(d[th])

The last line crashes the script and gives me a KeyError.

Am I missing something here? Shouldn't this work?

Does the dict lookup add another "filter" besides calling the hash method of the passed key?

EDIT:

After further research (see the answer on this question by Duncan: How can Python dict have multiple keys with same hash?) it seems to me that python thinks this is a hash collision and acts accordingly. Is there a way I can avoid that, so that calling d with keys th and "TestHasher" return the same object?

  • Having the same hash isn't the same as being equal. You've just created a hash collision, which dictionaries are designed to be able to cope with. – khelwood Aug 18 '18 at 16:53
  • You need to implement `__eq__` in addition to `__hash__`. – Aran-Fey Aug 18 '18 at 16:54

0 Answers0