There are several standard ways to make a class hashable, for example (borrowing from SO):
# assume X has 2 attributes: attr_a and attr_b
class X:
def __key(self):
return (self.attr_a, self.attr_b)
def __eq__(x, y):
return isinstance(y, x.__class__) and x.__key() == y.__key()
def __hash__(self):
return hash(self.__key())
Now suppose I have many classes that I want to make hashable. They are all immutable, with immutable attributes, and hashing all these attributes in bulk is acceptable (for a class with too many attributes, we would only want to hash a few attributes that are enough to avoid most collisions). Can I avoid writing __key()
method by hand for every class?
Would it be a good idea to make a base class that defines __key()
, __eq__
, and __hash__
for them? In particular, I'm not sure whether finding all the instance attributes that should go into __hash__
is doable. I know this is generally impossible, but in this case we can assume more about the object (e.g., it's immutable - after __init__
is finished, its attributes are all hashable, etc.).
(If the inheritance hierarchy won't work, perhaps a decorator would?)