Python – Is it a good idea to hash a Python class


For example, suppose I do this:

>>> class foo(object):
...     pass
>>> class bar(foo):
...     pass
>>> some_dict = { foo : 'foo',
... bar : 'bar'}
>>> some_dict[bar]
>>> some_dict[foo]
>>> hash(bar)
>>> id(bar)

Based on that, it looks like the class is getting hashed as its id number. Therefore, there shouldn't be any danger of worrying about, say, a bar hashing as either a foo or a bar or hash values changing if I mutate the class.

Is this behavior reliable, or are there any gotchas here?

Best Solution

Yes, any object that doesn't implement a __hash__() function will return its id when hashed. From Python Language Reference: Data Model - Basic Customization:

User-defined classes have __cmp__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns id(x).

However, if you're looking to have a unique identifier, use id to be clear about your intent. A hash of an object should be a combination of the hashes of its components. See the above link for more details.