Can anyone please explain how is it possible to get an object which is both hashable and mutable?
I have seen: Hashable, immutable it does not answer my question
I heard it is possible in python.
Can anyone please explain how is it possible to get an object which is both hashable and mutable?
I have seen: Hashable, immutable it does not answer my question
I heard it is possible in python.
Copyright © 2021 Jogjafile Inc.
Here is some code that shows you the effects of making an object both hashable and mutable. Note that the link you provided does actually answer your question in Andrew Jaffe's answer and the comments under it; I've added some code from this question about hashing in order to help explain.
The default for a python object's hash value is the object ID, which will not change during it's lifetime. A custom value can be provided by
__hash__
; however, in order to be useful, this must be translated into something that can be hashable, such as an integer or a string.Let's run this through and see what the outcomes are:
Anytime we want to look at the hash values, we can use
print(test_obj.__hash__())
. Try changing theint
and seeing if the hash changes. Also, since Python uses a random salt with str hashes to prevent collisions, note also that hashing this way will supply different hash values in different processes.We can demonstrate that the object is usable as a hashable object by testing if a dictionary will accept the object as a key. Dictionary keys cannot be lists, for example.
Try changing the list within the object, and seeing if it is still acceptable:
What if we need to go back?
Note how "first object" has been changed to "third object".
Putting all of this code together:
But what if we need to have a consistent, predictable hash value?
__hash()
doesn't have to usehash()
! It can return other values. This would mean making the process compatible though - otherwise you'll getTypeError: __hash__ method should return an integer
.Try converting the name into an integer:
What happens if you run the dictionary tests in this scenario?
You'll notice that instead of having two entries to the dictionary, you only get one - this is because changing the list does not change the hash value produced by the object.
Outcome of the original random hash dict tests:
Outcome of the second fixed hash dict tests: