I would like to write a class that can be used as a key in a hashable collections (e.g. in a dict). I know that user classes are by default hashable, but using id(self) would be the wrong thing here.
My class holds a tuple as member variable. Deriving from tuple doesn't seem like an option because in my constructor I don't get the same kind of arguments as a tuple constructor. But perhaps that's not a limitation?
What I need is basically the hash of a tuple the way a real tuple would give it.
hash(self.member_tuple) does just that.
The idea here is that two tuples can be equal without their id being equal.
If I implement my __cmp__() as follows:
def __cmp__(self, other):
return cmp(self, other)
will this automatically resort to hash(self) for the comparison? ... or should I implement it as follows:
def __cmp__(self, other):
return cmp(self.member_tuple, other)
My __hash__() function is implemented to return the hash of the held tuple, i.e.:
def __hash__(self):
return hash(self.member_tuple)
Basically, how do __cmp__() and __hash__() interact? I don't know whether in __cmp__() the other will already be a hash or not and whether I should compare against "my" hash (which would be the one of the held tuple) or against self.
So which one is the right one?
Can anyone shed any light on this and possibly point me to documentation?