3

So, I've done a lot of research on this and saw various other links and conferred with the Python documentation, however, I'm still a bit unclear on this.

Maybe the way I see classes in Python is a bit wrong.

As I understand, keys in a dictionary must be immutable. However, classes can be keys in a dictionary because of their default hash implementation (I think?). Why is this the case since classes are mutable?

For example,

class C:
    def __init__(self):
        self.val = 15
        self.array = []

c = C()

D = {c: 15}
c.val = 14
c.array.append(15)

print(D[c])

Why is this okay?

5
  • "Why doesn't changing things in your class change the hash?" because the output of the hash() function isn't dependent on the contents of the attributes by default (unless you explicitly override its implementation to be). My answer is correct but the part about the hash(c) == id(c) is incorrect, and I'm trying to understand why Commented Apr 27, 2023 at 20:18
  • Does this answer your question? What is the default __hash__ in python? Commented Apr 27, 2023 at 20:20
  • Not sure about that, but I think the generated hash for an object is related to its class and/or memory metadata, not its attributes. So since this metadata wouldn't change, the hash is the same Commented Apr 27, 2023 at 20:23
  • The requirement for keys in the dictionary is hashable, not immutable. In fact, even a mutable object such as list can be contained in a dictionary by subclassing it and defining a __hash__ method. Furthermore, you can change the hash value after you have put it in the dictionary. Of course, this is bad practice. Commented Apr 27, 2023 at 20:37
  • You're not using classes as keys there. Just an instance. Commented Apr 27, 2023 at 20:41

1 Answer 1

5

Instances of your C class are actually hashable, it comes with a default implementation of __hash__ which pertains to the identity of that object:

>>> hash(c) # calls c.__hash__()
306169194

This __hash__ implementation allows your instance to be used as a key in a dictionary.

This explains "Why doesn't changing things in your class change the hash?" — because the identity/reference of the instance doesn't change even if its contents do.

On older versions of python, this used to be exactly equal to the object's id, but from python 3 onwards, it seems to be some derivative of it. This post goes into the gory details on the hash implementation.


Now let's say you wanted to prevent instances of your class from being used as a key... you could then do this (from the documentation):

If a class that does not override __eq__() wishes to suppress hash support, it should include __hash__ = None in the class definition.

class C:
    def __init__(self):
        self.val = 15
        self.array = []

    __hash__ = None # suppressing hash support

c = C()

And now you get a familiar sounding TypeError if you attempt to retrieve the hash of c:

>>> hash(c)
# TypeError: unhashable type: 'C'

Naturally, this also implies you cannot use c as a dictionary key anymore (IOW trying to initialize {c: 15} would also throw the same TypeError since c is not hashable).

Sign up to request clarification or add additional context in comments.

2 Comments

Why doesn't changing things in your class change the hash?
@John answered under your question but to summarize, the default implementation of hash() is to return a static number that has to do with the object's reference/identity, independent of its contents.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.