Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In Python, I know that the value __hash__ returns for a given object is supposed to be the same for the lifetime of that object. But, out of curiosity, what happens if it isn't? What sort of havoc would this cause?

class BadIdea(object):
  def __hash__(self):
    return random.randint(0, 10000)

I know __contains__ and __getitem__ would behave strangely, and dicts and sets would act odd because of that. You also might end up with "orphaned" values in the dict/set.

What else could happen? Could it crash the interpreter, or corrupt internal structures?

share
    
Such code should never directly "crash" or "corrupt" the run-time, but dict/set usage will indeed become .. problematic. –  user2864740 5 mins ago
add comment

1 Answer

Your main problem would indeed be with dicts and sets. If you insert an object into a dict/set, and that object's hash changes, then when you try to retrieve that object you will end up looking in a different spot in the dict/set's underlying array and hence won't find the object. This is precisely why dict keys should always be immutable.

Could it crash the interpreter, or corrupt internal structures?

No, this won't happen.

share
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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