From ba496539da2f108234103fc761ace8454490070c Mon Sep 17 00:00:00 2001 From: Petr Viktorin Date: Wed, 18 Mar 2015 14:14:38 +0100 Subject: [PATCH 1/2] Define Py_RICHCOMPARE to ease writing rich comparison functions --- Doc/c-api/typeobj.rst | 12 ++++++++++++ Include/object.h | 10 ++++++++++ 2 files changed, 22 insertions(+) diff --git a/Doc/c-api/typeobj.rst b/Doc/c-api/typeobj.rst index eb63705..a2d6b71 100644 --- a/Doc/c-api/typeobj.rst +++ b/Doc/c-api/typeobj.rst @@ -613,6 +613,18 @@ type objects) *must* have the :attr:`ob_size` field. | :const:`Py_GE` | ``>=`` | +----------------+------------+ + The following macro is defined to ease writing rich comparison functions: + + .. c:function:: PyObject *Py_RICHCOMPARE(VAL_A, VAL_B, int op) + + Compares two arguments orderable by C comparison operators (such as C + ints or floats). The third argument specifies the requested operation, + as for the rich comparison function. + Evaluates to a new reference to ``Py_True`` or ``Py_False``, depending + on the result of the comparison. + + .. versionadded:: 3.5 + .. c:member:: long PyTypeObject.tp_weaklistoffset diff --git a/Include/object.h b/Include/object.h index e29608a..90cff4f 100644 --- a/Include/object.h +++ b/Include/object.h @@ -880,6 +880,16 @@ PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */ #define Py_GT 4 #define Py_GE 5 +/* Macro for implementing rich comparisons */ +#define Py_RICHCOMPARE(val1, val2, op) ( \ + ((op) == Py_EQ) ? PyBool_FromLong((val1) == (val2)) : \ + ((op) == Py_NE) ? PyBool_FromLong((val1) != (val2)) : \ + ((op) == Py_LT) ? PyBool_FromLong((val1) < (val2)) : \ + ((op) == Py_GT) ? PyBool_FromLong((val1) > (val2)) : \ + ((op) == Py_LE) ? PyBool_FromLong((val1) <= (val2)) : \ + ((op) == Py_GE) ? PyBool_FromLong((val1) >= (val2)) : \ + (Py_INCREF(Py_NotImplemented), Py_NotImplemented)) + /* Maps Py_LT to Py_GT, ..., Py_GE to Py_LE. * Defined in object.c. */ -- 2.1.0