user4237459
user4237459

Reputation:

Range ordering and inequality comparison

I was trying to recreate Python's range as a learning exercise, and noticed that ranges had range.__gt__, range.__ge__ etc. attribute. It was specifically defined in range, as range also has 8 attributes with the qualified name of object.__...__.

I was wondering what the range comparisons are used for. Any attempt at range(*x) <= range(*y) raises a TypeError: unorderable types: range() > range()

Upvotes: 2

Views: 379

Answers (1)

poke
poke

Reputation: 388313

The Python 3 range object defines the following rich comparisons (taken from the C source):

static PyObject *
range_richcompare(PyObject *self, PyObject *other, int op)
{
    int result;
    if (!PyRange_Check(other))
        Py_RETURN_NOTIMPLEMENTED;
    switch (op) {
    case Py_NE:
    case Py_EQ:
        result = range_equals((rangeobject*)self, (rangeobject*)other);
        if (result == -1)
            return NULL;
        if (op == Py_NE)
            result = !result;
        if (result)
            Py_RETURN_TRUE;
        else
            Py_RETURN_FALSE;
    case Py_LE:
    case Py_GE:
    case Py_LT:
    case Py_GT:
        Py_RETURN_NOTIMPLEMENTED;
    default:
        PyErr_BadArgument();
        return NULL;
    }
}

As you can see, the only comparisons that are actually implemented are NE and EQ which are for inequality and equality. The other comparisons, like larger-equals, larger-than, etc., are all Py_RETURN_NOTIMPLEMENTED, so while they are “technically” implemented (as in the builtin object defines the comparison methods), they throw a NotImplementedError.

Upvotes: 1

Related Questions