Вопрос

It'd seem reasonable to make int.__hash__ simply return the value. Sure enough, that seems to be how CPython implements it:

>>> hash(1)
1
>>> hash(2)
2
>>> hash(123456789)
123456789
>>> hash(-123456789)
-123456789

Ok, so does this hold true for all most integer x?

>>> [x for x in range(-10000, 10000) if hash(x) != x]
[-1]

Huh?

>>> hash(-1)
-2

Why is -1 the exception to this rule?

Это было полезно?

Решение

From http://effbot.org/zone/python-hash.htm:

The hash value -1 is reserved (it’s used to flag errors in the C implementation). If the hash algorithm generates this value, we simply use -2 instead.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top