Take the 2-minute tour ×

Following on from this question, I'm interested to know when is a python object's hash computed?

  1. At an instance's __init__ time,
  2. The first time __hash__() is called,
  3. Every time __hash__() is called, or
  4. Any other opportunity I might be missing?

I looked through python docs and couldn't dig out this information anywhere. I realise this may vary depending on the type of the object, so let's say for str types.

Also, out of curiosity can anyone enlighten me as to why len(["wtf is so special about the integer -1?" for i in xrange(-1000000,1000000) if hash(i) != i]) != 0 is True?

share|improve this question
3 is out as I've read it is cached the first time it is called. I would assume the 2nd option is right but as I'm not sure I won't post it as an answer :) –  rplnt Oct 4 '11 at 12:51
@rplnt: wrong; that's merely when talking of a dictionary. Its hash will be stored in the dictionary, but that's not true of general hashing. –  Chris Morgan Oct 7 '11 at 0:37

3 Answers 3

up vote 9 down vote accepted

The hash is generally computed each time it's used, as you can quite easily check yourself (see below). Of course, any particular object is free to cache its hash. For example, CPython strings do this, but tuples don't (see e.g. this rejected bug report for reasons).

The hash value -1 signalizes an error to CPython. This is because C doesn't have exceptions, so it needs to use the return value. When a Python object's __hash__ returns -1, CPython will actually silently change it to -2.

See for yourself:

class HashTest(object):
    def __hash__(self):
        print 'Yes! __hash__ was called!'
        return -1

hash_test = HashTest()

# All of these will print out 'Yes! __hash__ was called!':

print '__hash__ call #1'

print '__hash__ call #2'

print 'hash call #1'

print 'hash call #2'

print 'Dict creation'
dct = {hash_test: 0}

print 'Dict get'

print 'Dict set'
dct[hash_test] = 0

print '__hash__ return value:'
print hash_test.__hash__()  # prints -1
print 'Actual hash value:'
print hash(hash_test)  # prints -2
share|improve this answer

From here:


As integer's hash is integer itself it's just changed right away.

share|improve this answer

It is easy to see that option #3 holds for user defined objects. This allows the hash to vary if you mutate the object, but if you ever use the object as a dictionary key you must be sure to prevent the hash ever changing.

>>> class C:
    def __hash__(self):
        print("__hash__ called")
        return id(self)

>>> inst = C()
>>> hash(inst)
__hash__ called
>>> hash(inst)
__hash__ called
>>> d = { inst: 42 }
__hash__ called
>>> d[inst]
__hash__ called

Strings use option #2: they calculate the hash value once and cache the result. This is safe because strings are immutable so the hash can never change, but if you subclass str the result might not be immutable so the __hash__ method will be called every time again. Tuples are usually thought of as immutable so you might think the hash could be cached, but in fact a tuple's hash depends on the hash of its content and that might include mutable values.

share|improve this answer

Your Answer


