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

Steven Bethard steven.bethard at gmail.com
Wed Dec 22 13:10:05 EST 2004


Nick Coghlan wrote:
> The longer I consider it, the more this seems like a valid analogy. 
> There is nothing preventing dictionaries from having a rehash() method.
> 
> Consider:
> # Mutate some value in mylist
> mylist.sort()
> 
> # Mutate some key in mydict
> mydict.rehash()

Well, you can already get the equivalent of rehash right now by creating 
a new dict from the items of the old one:

 >>> class hashablelist(list):
...     def __hash__(self):
...         return hash(tuple(self))
...
 >>> hlist = hashablelist([0])
 >>> d = {hlist:1}
 >>> hlist[0] = 1
 >>> d[hlist]
Traceback (most recent call last):
   File "<interactive input>", line 1, in ?
KeyError: [1]
 >>> d = dict(d.items())
 >>> d[hlist]
1

Of course, if rehash worked in place, you could probably do some 
optimizations to only rehash the necessary items.

Steve



More information about the Python-list mailing list