confusing doc: mutable and hashable

MRAB python at mrabarnett.plus.com
Sat Apr 28 19:36:29 EDT 2012


On 28/04/2012 23:30, Temia Eszteri wrote:
>>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
>
> Well, if worst comes to worst and you wind up in a programming
> situation where you needed to make a mutable object as a hash entry,
> it's still possible to subclass the object type and have __hash__()
> return the object's ID instead, right?
>
> I can only think of a few edge cases where that could even possibly be
> required though, such as membership testing for something and having a
> callback associated with each set of members...
>
If objects x and y of the same class are mutable and you want them to
have the same hash if x == y then having __hash__() return the object's
ID is not what you want.



More information about the Python-list mailing list