title: Implementing complex number comparison in Python?
body: <p>I know that comparison operators with complex numbers can't be defined in general. That is why python throws a <code>TypeError</code> exception when trying to use out-of-the-box complex comparison. I understand why this is the case (please don't go off topic trying to explain why two complex numbers can't be compared).</p>
  
  <p>That said, in this particular case I would like to implement complex number comparison based on their magnitudes. In other words, for <code>z1</code> and <code>z2</code> complex values, then <code>z1 &gt; z2</code> if-and-only-if <code>abs(z1) &gt; abs(z2)</code>, where <code>abs()</code> implements complex number magnitude, as in <code>numpy.abs()</code>.</p>
  
  <p>I have come up with a solution (at least I think I have) as follows:</p>
  
  <pre class="lang-python prettyprint-override"><code>import numpy as np
  
  class CustomComplex(complex):
      def __lt__(self, other):
          return np.abs(self) &lt; np.abs(other)
      def __le__(self, other):
          return np.abs(self) &lt;= np.abs(other)
      def __eq__(self, other):
          return np.abs(self) == np.abs(other)
      def __ne__(self, other):
          return np.abs(self) != np.abs(other)
      def __gt__(self, other):
          return np.abs(self) &gt; np.abs(other)
      def __ge__(self, other):
          return np.abs(self) &gt;= np.abs(other)
  
  complex = CustomComplex
  </code></pre>
  
  <p>This seems to work, but I have a few questions:</p>
  
  <ol>
  <li>Is this the way to go or is there a better alternative?</li>
  <li>I would like my package to transparently work with the built-in <code>complex</code> data type as well as <code>numpy.complex</code>. How can this be done elegantly, without code duplication?</li>
  </ol>