Alex
Alex

Reputation: 19823

why are custom objects hashable (and usable in dict) in python?

Newbie question: in order for an object to be used as a key in dict it needs to be hashable. It's clear that immutable types can be used as keys while mutable types cannot. However, if I define a class which is mutable, apparently it can still be used as a key. In the code below my_obj is a reference to a memory slot containing an object of type RandomObject. That memory slot contains a reference (x) to 25 but this reference can be changed to point to anything else. This is confusing for me, why does it work? Moreover, my_obj can be made to reference an entirely new instance of RandomObject. If hashing occurs on the actual object (and not the memory address of the reference) how can this work?

class RandomObject:
    def __init__(self, x):
        self._x = x

d = {"hi": 1, "bye": 2}
my_obj = RandomObject(25)
d[my_obj] = 3
print(d)
#{'hi': 1, 'bye': 2, <__main__.RandomObject object at 0x0000000005B75D30>: 3}

Upvotes: 4

Views: 995

Answers (1)

user2357112
user2357112

Reputation: 281252

Your class inherits object.__eq__ and object.__hash__, which work by identity. Hashing doesn't directly care about mutability; it only cares about mutability that affects == comparisons. When == is by identity, no mutation will affect == comparisons.

Upvotes: 11

Related Questions