78

Here is my code:

class Hero:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return self.name + str(self.age)

    def __hash__(self):
        print(hash(str(self)))
        return hash(str(self))

heroes = set()

heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407
print(len(heroes)) # gets 1

heroes.add(Hero('Lara Miheenko', 17)) # gets hash -2822451113328084695
print(len(heroes)) # gets 2

heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407
print(len(heroes)) # gets 3! WHY?

Why is this happening?
The 1st and the 3rd object have same content and same hash but len() tells about 3 unique objects?

8
  • Not sure, but your probably need __eq__ or __cmp__: docs.python.org/glossary.html#term-hashable
    – nhahtdh
    Jun 12, 2012 at 9:58
  • 4
    That aside, this isn’t the best hash function (because you’re not hashing a general string, one of the string components has much lower entropy because it’s known to consist of digits). For a trivial but pretty effective fix, take the hash values of the objects separately and xor them. For more magic, add them scaled by a prime number constant. Jun 12, 2012 at 10:49
  • @KonradRudolph: There's an implied assumption in your comment – specifically that a "good" hash is needed for the set to perform well. This is not the case with Python's set implementation; see this comment from the Python sources for further explanations. Jun 12, 2012 at 22:44
  • 5
    @Sven I somewhat disagree. First, this is a CPython implementation detail, not guaranteed by Python. Second, this still assumes high entropy in the lower bits (and to some extent later in the higher bits, for collision). You still need good randomness, only not over the whole number range. Third, the comment, while detailed, is somewhat murky on the theory side. I’m not very confident in this far-from-rigorous analysis. I want a rigorous, peer-reviewed study on that, not some hand-waving. Jun 13, 2012 at 6:56
  • 12
    @KonradRudolph: The hash function should actually be implemented as hash((self.name, self.age)), deferring the details to the tuple hash algorithm of the Python implementation, which is hopefully optimised to work well with the set and dict implementations. And I agree that the linked comment is not a rigorous analysis. I find it interesting anyway; extensive and thorough benchmarking, as has been performed for the CPython dict implementation, might lead to better performance in practice than a rigorous analysis. Jun 13, 2012 at 11:18

3 Answers 3

81

You also need to define __eq__() in a compatible way with __hash__() – otherwise, equality will be based on object identity.

On Python 2, it is recommended you also define __ne__ to make != consistent with ==. On Python 3, the default __ne__ implementation will delegate to __eq__ for you.

6
  • 9
    Indeed, after checking if the hashes are equal, the dict/set must also check for actual equality in case of hash collision. Jun 13, 2012 at 13:43
  • @user2357112 Definig __ne__ not required to make a type hashable, right? It may be good idea to define it, since otherwise != will have rather weird semantics, but if all you want to do is using the type in a set or dictionary, you don't really need it. Oct 21, 2017 at 12:37
  • @SvenMarnach: Technically, sets and dicts don't use != anywhere, but actually relying on that is a recipe for nasty bugs. Even if sets don't use !=, someone's probably gonna. You can reword it if you want, but I think the answer should definitely mention __ne__; the spirit of the question definitely seems more "how do I do things right" than "what is the bare minimum needed to get this code snippet to produce the expected output". Oct 21, 2017 at 18:25
  • @user2357112 I'm not sure I fully agree; it really depends on the scope of what you are working on. And the fact that set and dict don't use != isn't an accident, but documented and guaranteed behaviour. The Python 2 glossary also defines hashable as basically "having __hash__ and (__eq__ or __cmp__)" without any mention of __ne__. Anyway, I agree that it never hurts to define it, and slightly modified the wording. Oct 22, 2017 at 12:17
  • In order for a set.add(x) to include x into the set, where x is a user-defined type, both hash(x) must return a unique integer (i.e., one that is not already seen when hash() is called on each of the objects already in a set) AND __eq__(self,x) must be false. In other words, if two instances hash to the same value OR is equal by __eq__ definition, then it is not included from the set when you call set.add(x). Is this correct?
    – Minh Tran
    Feb 21, 2018 at 16:45
29

Here is the the entire code :

class Hero:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return self.name + str(self.age)

    def __hash__(self):
        print(hash(str(self)))
        return hash(str(self))

    def __eq__(self,other):
        return self.name == other.name and self.age== other.age



heroes = set()
heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407
print(len(heroes)) # gets 1

heroes.add(Hero('Lara Miheenko', 17)) # gets hash -2822451113328084695
print(len(heroes)) # gets 2

heroes.add(Hero('Zina Portnova', 16)) # gets hash -8926039986155829407
print(len(heroes)) # gets 2 

The function recognises the __eq__ and as such the len is 2.

0
9

The Python documentation might be helpful:

If a class does not define a __cmp__() or __eq__() method it should not define a __hash__() operation either;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.