0

Why do the negative integers -1 and -2 have the same hash?

>>> hash(-1)
-2
>>> hash(-2)
-2
amitjans
  • 83
  • 1
  • 7
  • 2
    The source code of `long_hash` seems to intentionally avoid returning -1 (in every place where it could return -1, it does something to ensure that it returns something else). IDK where this desire to avoid -1 comes from though. – harold Dec 16 '22 at 10:18
  • python builtin hash is not exactly designed for integers, because it will just return the int itself most of the time. It is mostly used for objects. but no, it is not a bug. – hash Dec 16 '22 at 10:18
  • 2
    "Have I discovered a bug in one of the most simple functions of a language used by millions which can be demonstrated in two short lines?" — *Probably not.* – deceze Dec 16 '22 at 10:19
  • 2
    @harold: `-1` is reserved for an error indicator. It's an invalid hash value. Python will even automatically change your hash if you try to return `-1` from a `__hash__` method you write, but classes written in C have to manually avoid returning `-1`. – user2357112 Dec 16 '22 at 10:24
  • This is a dup, I know it is, but I can't find it. – President James K. Polk Dec 16 '22 at 16:24

1 Answers1

2

No, it's not a bug, as stated in the help text of the hash function:

>>> help(hash)
Help on built-in function hash in module builtins:

hash(obj, /)
    Return the hash value for the given object.
    
    Two objects that compare equal must also have the same hash value, but the
    reverse is not necessarily true.

i.e., It's not necessarily true that two objects that have the same hash value compare equal.

Interestingly, the documentation has a different wording and doesn't explicitly mention this, it only says

Numeric values that compare equal have the same hash value

mkrieger1
  • 19,194
  • 5
  • 54
  • 65