hashing mutable instances

Bernhard Herzog bh at intevation.de
Thu Oct 30 08:28:25 EST 2003


Thomas Heller <theller at python.net> writes:

> Michael Hudson <mwh at python.net> writes:
>
>> Try inserting a bunch of instances of 
>>
>> class C:
>>     def __hash__(self): return 0
>>
>> into a dictionary.
>
> I've though about using something like this in production code
> to be able to store mutable instances in a dict.
> Performance problems aside (since there are only a couple of key/value
> pairs in the dict), is it such a bad idea?

IMO it depends on what equality means for instances. E.g. if two
instances are only equal if they're identical, i.e. a == b is equivalent
to a is b, then defining __hash__ can be very useful, because then you
can use them in dictionaries and mutability doesn't really matter
because no change to one instance can make it equal to a nother
instance.

I'd define __hash__ to return id(self), though, so that the hash values
are different for different instances to reduce collisions.

This also seems to be what class objects in Python do:

>>> class C(object):
...     pass
... 
>>> hash(C)
135622420
>>> id(C)
135622420
>>> 

   Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
Thuban                                  http://thuban.intevation.org/




More information about the Python-list mailing list