Python Mutable Class Instances as Dictionary Keys

Mutable builtins in #Python cannot be dict keys. But instances of your (mutable) classes can! class C: def __init__(self, x): self.x = x c = C(10) d = {c:10} # No error! print(d[c]) # prints 10

  • No alternative text description for this image

You _can_, but I wouldn’t recommend it. Try this with your class in CPython 😕: s = set() for I in range(20000): h = hash(C(i)) s.add(h) assert len(s) == 1

That's an instance not a class you are using as a key.

But users beware! Another object with the same value for .x can’t be used to fetch the item from the dictionary. It must be the same object in this case. That can lead to unexpected surprises… But this opens a whole new can of worms…

See more comments

To view or add a comment, sign in

Explore content categories