title: Elegant ways to support equivalence ("equality") in Python classes
body: <p>When writing custom classes it is often important to allow equivalence by means of the <code>==</code> and <code>!=</code> operators. In Python, this is made possible by implementing the <code>__eq__</code> and <code>__ne__</code> special methods, respectively. The easiest way I've found to do this is the following method:</p>
  
  <pre><code>class Foo:
      def __init__(self, item):
          self.item = item
  
      def __eq__(self, other):
          if isinstance(other, self.__class__):
              return self.__dict__ == other.__dict__
          else:
              return False
  
      def __ne__(self, other):
          return not self.__eq__(other)
  </code></pre>
  
  <p>Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing <code>__dict__</code>s?</p>
  
  <p><strong>Note</strong>: A bit of clarification--when <code>__eq__</code> and <code>__ne__</code> are undefined, you'll find this behavior:</p>
  
  <pre><code>&gt;&gt;&gt; a = Foo(1)
  &gt;&gt;&gt; b = Foo(1)
  &gt;&gt;&gt; a is b
  False
  &gt;&gt;&gt; a == b
  False
  </code></pre>
  
  <p>That is, <code>a == b</code> evaluates to <code>False</code> because it really runs <code>a is b</code>, a test of identity (i.e., "Is <code>a</code> the same object as <code>b</code>?").</p>
  
  <p>When <code>__eq__</code> and <code>__ne__</code> are defined, you'll find this behavior (which is the one we're after):</p>
  
  <pre><code>&gt;&gt;&gt; a = Foo(1)
  &gt;&gt;&gt; b = Foo(1)
  &gt;&gt;&gt; a is b
  False
  &gt;&gt;&gt; a == b
  True
  </code></pre>