python at mrabarnett
Apr 28, 2012, 4:36 PM
Post #6 of 10
On 28/04/2012 23:30, Temia Eszteri wrote:
>>Yes, you're right. Being mutable and hashable are orthogonal properties.
>> 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
> 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.