Let's say we have a custom node class like this:
class Node:
def __init__(self, val, next, random):
self.val = val
self.next = next
self.random = random
I have a node object that I'd like to use as a key for a dictionary.
My understanding is that an object should be immutable and hashable for it to be reliably used as a dictionary key, because a mutable object could result in a changing hash values and this object is mutable.
I know python does allow custom mutable objects to be used as dictionary keys, how does that work?
Update: Referenced links do not touch upon the mutability aspect of the custom object. They just provide a method to override the default implementation of the hash function. This question should be reopened as it is different from the referenced "duplicate" questions.
Answer: Default implementation of hash method for custom mutable object uses identity, which is guaranteed to be unique and constant for object's lifetime. A mutable custom object SHOULD NOT be overriding the default implementation of hash function. More detailed answer is provided below.