confusing doc: mutable and hashable

Chris Rebert clp2 at rebertia.com
Sat Apr 28 14:35:12 EDT 2012


On Sat, Apr 28, 2012 at 11:09 AM,  <laymanzheng at gmail.com> wrote:
> I'm just learning Python. The python doc about mutable and hashable is confusing to me.
>
> In my understanding, there is no directly relation between mutable and hashable in Python. Any class with __hash__ function is "hashable".
>
> According the wiki: http://en.wikipedia.org/wiki/Immutable_object
>
> In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created.[1] This is in contrast to a mutable object, which can be modified after it is created.
>
> We surely can define __hash__ function in user-define class and the instance of that class can be changed thus mutable.
>
> But following statement seems correct in practice but not technically. Any comments on this?

Correct. Pedantically, you can define __hash__() on mutable objects;
it's just not very useful or sensible, so people generally don't. As
http://docs.python.org/reference/datamodel.html#object.__hash__ states
[emphasis added]:

"If a class defines *mutable* objects and implements a __cmp__() or
__eq__() method, it *should not* implement __hash__(), since hashable
collection implementations require that a object’s hash value is
immutable (if the object’s hash value changes, it will be in the wrong
hash bucket)."

> ------------------------
> http://docs.python.org/py3k/library/stdtypes.html#set-types-set-frozenset:
>  Since it is mutable, it has no hash value and cannot be used as either a dictionary key or as an element of another set.
> ------------------------

Cheers,
Chris



More information about the Python-list mailing list