Mutable objects which define __hash__ (was Re: Why are tuples immutable?)

Antoon Pardon apardon at forel.vub.ac.be
Thu Dec 23 06:16:39 EST 2004


Op 2004-12-23, Nick Coghlan schreef <ncoghlan at iinet.net.au>:
> Steven Bethard wrote:
>> Of course, if rehash worked in place, you could probably do some 
>> optimizations to only rehash the necessary items.
>
> Yep, especially given this little critter from dictobject.h which contains 
> everything needed to spot mutated objects:
>
> typedef struct {
> 	long me_hash;      /* cached hash code of me_key */
> 	PyObject *me_key;
> 	PyObject *me_value;
> } PyDictEntry;
>
> So the major downside to giving standard mutable objects hash methods is that 
> dictionaries then suffer from the 'mutation without resorting' problem that 
> sorted lists can currently suffer from.
>
> As I said to Antoon, I no longer have any theoretical objection to the idea of 
> mutable objects with a variable hash. I do, however, have a practical objection 
> - mutating a dict's keys without calling rehash() could lead to some extremely 
> subtle bugs that the interpreter can't really help identify. It just seems far 
> too easy to inadvertently burn yourself by altering an object that is being used 
> as a dictionary key.

Well then we will have to agree to disagree on this point. Python allows
one variable to mutate by mutating another variable. That is IMO the
great burning stick in Python. That this also causes problems for
dictionaries is just a consequent of that and doesn't warrant special
protection that is not available elsewhere in the language.

I don't understand why the ease of mutating an object that should remain
stable should cause more unease in a person just because the subject
is dictionary keys, except maybe because of custom.

But I'm obviously in the minority here.

-- 
Antoon Pardon



More information about the Python-list mailing list