I come from Java where even mutable objects can be "hashable".
And I am playing with Python 3.x these days just for fun.
Here is the definition of hashable in Python (from the Python glossary).
hashable
An object is hashable if it has a hash value which never changes during its lifetime (it needs a
__hash__()method), and can be compared to other objects (it needs an__eq__()method). Hashable objects which compare equal must have the same hash value.Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
All of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their
id().
I read it and I am thinking... Still... Why didn't they make in Python even mutable objects hashable? E.g. using the same default hashing mechanism as for user-defined objects i.e. as described by the last 2 sentences above.
Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().
This feels somewhat weird... so user-defined mutable objects are hashable (via this default hashing mechanism) but built-in mutable objects are not hashable. Doesn't this just complicate things? I don't see what benefits it brings, could someone explain?
id()because it can't be modified. Users would generally expect hashing a user-defined class to behave more like an immutable object (even though it is mutable) so that's what it does, although of course you can make it behave any way you like.id.hashCodevalues are based on container contents. For example, here are the List docs. Anything else would be broken and/or useless, sinceequalsis based on collection contents.sethas alistin it. E.g. if you didx = {[1]}, then[1] in xwould returnFalse. It might be hard to say what is or is not confusing to a beginner, but broken semantics can't be good...