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

Antoon Pardon apardon at forel.vub.ac.be
Thu Dec 23 05:56:42 EST 2004


Op 2004-12-22, Nick Coghlan schreef <ncoghlan at iinet.net.au>:
>> I'm currently not under the impression I'm able to. Sure I could
>> implement the above mentioned classes, but my feeling is that
>> should I present them here, nobody would be waiting for them.
>> Not because they would be unusfull, but because they go against
>> the current paradigm.
>
> As I see it, you have a couple of courses available:
>
> If you're into pain, consider further developing the 'rehash' idea, and the 
> option of adding hash methods to the mutable builtins. You've persuaded me that 
> the idea is not entirely unreasonable. However, I mention pain, because you'd 
> still have work to do persuading enough people (including me) that the 
> additional hard to detect bugs this adds to the language would be worth it.
>
> I don't really recommend that option.

How about this:

  from UserDict import UserDict

  class RehashableDict(UserDict):

    def rehash(self):

      dic = {}
      for k,v in self.data.iteritems():
        dic[k] = v
      self.data = dic


This works as far as I have tested things out.


I don't think I would recommend adding hash methods to mutable builtins.
Storing keys by identity or value both can make sense for these kind
of objects. And since python prefers not to guess I think it is a good thing
there is no default hash for mutable objects.

-- 
Antoon Pardon



More information about the Python-list mailing list