making hashable classes. Re: Fast union/intersection of two sequences?

Aaron Watters (aaron@funcity.njit.edu)
Wed, 25 Jan 1995 14:06:56 GMT

RE: making classes hashable...

In article <199501241925.LAA04106@infoseek.com> Jim Roskind <jar@infoseek.com> writes:
>> Date: Tue, 24 Jan 1995 13:06:22 -0500
>> From: Skip Montanaro <skip@automatrix.com>
>If the object has some real innards (like a string and an index), then
>you would probably want something like:
>
> def __init__(self, str, val):
> self.str = str
> self.val = val
>
> def __hash__(self):
> return hash(self.str) + hash(self.val)

Whoops. Watch out for
OverflowError: integer addition
I suggest using bit operations, EG
def __hash__(self):
return hash(self.str) ^ ~ hash(self.val)

and it might be a good idea to avoid symmetrical functions in case you
end up hashing
thing(1,2,3), thing(2,1,3), thing(1,3,2),...
so they won't hash to the same value. -a.
===
The problem with doing things to extend your life is that all those
extra years come at the end, when you're old. (from a New Yorker cartoon).