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

Steven Bethard steven.bethard at
Wed Dec 22 19:10:05 CET 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]

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


More information about the Python-list mailing list