In [1]:
%load_ext Cython

In [2]:
%%cython
from cpython.object cimport Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, Py_GE

cdef class R:
    """Extension type that supports rich comparisons."""
    cdef double data
    def __init__(self, d):
        self.data = d
    def __richcmp__(x, y, int op):
        """a > b is equivalent to R.__richcmp__(a, b, Py_GT)."""
        cdef:
            R r
            double data
        # Make r always refer to the R instance.
        # using type casting 'cdef R r = y'
        r, y = (x, y) if isinstance(x, R) else (y, x)
        
        data = r.data
        if op == Py_LT:
            return data < y
        elif op == Py_LE:
            return data <= y
        elif op == Py_EQ:
            return data == y
        elif op == Py_NE:
            return data != y
        elif op == Py_GT:
            return data > y
        elif op == Py_GE:
            return data >= y
        else:
            assert False

In [3]:
r = R(10)

In [4]:
r < 20 and 20 > r


Out[4]:
True

In [5]:
r > 20 or 20 < r


Out[5]:
False

In [6]:
0 <= r <= 100


Out[6]:
True

In [7]:
r == 10


Out[7]:
True

In [8]:
r == 20


Out[8]:
False

In [9]:
20 == r


Out[9]:
False