On 4/28/2012 20:09, laymanzh...@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?
Thanks,
Andy
------------------------
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.
------------------------
Yes, you're right. Being mutable and hashable are orthogonal properties.
The implication
mutable => non hashable
is just a design choice.
The reason for such a choice is the following. If a key-element pair K:X
is added to a container C and then K is changed by some external Python
code without letting C know of this change, C may become inconsistent.
Some containers (e.g. set) assume that K=X and just take X. Modifying X
is equivalent to modifying K in the example above.
These kinds of problems are avoided if mutable objects can't be keys.
Some containers require that keys be hashable, but since, by design,
mutable objects can't be keys, there's no reason for them to be hashable
either.
Kiuhnm
--
http://mail.python.org/mailman/listinfo/python-list