hashing mutable instances
bh at intevation.de
Thu Oct 30 14:28:25 CET 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
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):
Intevation GmbH http://intevation.de/
More information about the Python-list