Take the 2-minute tour ×

When implementing a class with multiple properties (like in the toy example below), what is the best way to handle hashing?

I guess that the __eq__ and __hash__ should be consistent, but how to implement a proper hash function that is capable of handling all the properties?

class AClass:
  def __init__(self):
      self.a = None
      self.b = None

  def __eq__(self, other):
      return other and self.a == other.a and self.b == other.b

  def __ne__(self, other):
    return not self.__eq__(other)

  def __hash__(self):
      return hash((self.a, self.b))

I read on this question that tuples are hashable, so I was wondering if something like the example above was sensible. Is it?

share|improve this question
add comment

3 Answers

up vote 16 down vote accepted

__hash__ should return the same value for objects that are equal. It also shouldn't change over the lifetime of the object; generally you only implement it for immutable objects.

A trivial implementation would be to just return 0. This is always correct, but performs badly.

Your solution, returning the hash of a tuple of properties, is good. But note that you don't need to list all properties that you compare in __eq__ in the tuple. If some property usually has the same value for inequal objects, just leave it out. Don't make the hash computation any more expensive than it needs to be.

Edit: I would recommend against using xor to mix hashes in general. When two different properties have the same value, they will have the same hash, and with xor these will cancel eachother out. Tuples use a more complex calculation to mix hashes, see tuplehash in tupleobject.c.

share|improve this answer
As you said hash functions usually only make sense for immutable objects. Hence it is possible to calculate the hash-value once in __init__. –  Björn Pollex Oct 23 '10 at 19:20
+1 for the return 0 hash function - I've always thought that anything else is premature optimisation :-). (I'm only half kidding). –  Scott Griffiths Oct 23 '10 at 20:38
@BjörnPollex Rather than doing it in __init__, you can just cache the value in __hash__. That way if __hash__ is never called, you didn't waste either time or memory. I assume checking whether the value has been already cached isn't expensive is it? (Not sure if it's best through exception or explicit if). –  max Apr 22 '12 at 5:59
It's unfortunate that Python does not make a combine_hashes function available. –  larsmans Sep 20 '12 at 11:34
It's not implemented in things like dict or list, the justification being that changing the hash of an object that already belongs to, e.g., a set wreaks havoc on the set's internal data structures. –  javawizard Sep 5 '13 at 22:03
show 1 more comment

Documentation for object.hash(self)


def __hash__(self):
    return hash(self.a) ^ hash(self.b)
share|improve this answer
It will work, but it's bad that if you exchange self.a and self.b then you'll get the same hash while it will be the other "object". –  eigenein Jun 20 '11 at 21:16
"somehow mix together (e.g. using exclusive or" is a pretty flexible set of requirements. If it actually matters, then (hash(self.a)<<1) ^ hash(self.b) might be better. There's no general answer, just a general guideline that has to be modified based on the specific application. –  S.Lott Jun 20 '11 at 21:18
add comment

It's dangerous to write

def __eq__(self, other):
  return other and self.a == other.a and self.b == other.b

because if your rhs (i.e., other) object evaluates to boolean False, it will never compare as equal to anything!

In addition, you might want to double check if other belongs to the class or subclass of AClass. If it doesn't, you'll either get exception AttributeError or a false positive (if the other class happens to have the same-named attributes with matching values). So I would recommend to rewrite __eq__ as:

def __eq__(self, other):
  return isinstance(other, self.__class__) and self.a == other.a and self.b == other.b

If by any chance you want an unusually flexible comparison, which compares across unrelated classes as long as attributes match by name, you'd still want to at least avoid AttributeError and check that other doesn't have any additional attributes. How you do it depends on the situation (since there's no standard way to find all attributes of an object).

share|improve this answer
add comment

Your Answer


