Given two PyObject*
s, how can I compare them in C API?
I thought of a == b
at first, but it's clearly incorrect since it would compare the pointer and not the object. I'm looking for a == b
(not a is b
) Python equivalent in Python C API.
Given two PyObject*
s, how can I compare them in C API?
I thought of a == b
at first, but it's clearly incorrect since it would compare the pointer and not the object. I'm looking for a == b
(not a is b
) Python equivalent in Python C API.
You are looking for the PyObject_RichCompare
function:
PyObject *result = PyObject_RichCompare(a, b, Py_EQ);
From the documentation:
PyObject* PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)
Return value: New reference.
Compare the values of
o1
ando2
using the operation specified byopid
, which must be one ofPy_LT
,Py_LE
,Py_EQ
,Py_NE
,Py_GT
, orPy_GE
, corresponding to<
,<=
,==
,!=
,>
, or>=
respectively. This is the equivalent of the Python expressiono1 op o2
, whereop
is the operator corresponding toopid
. Returns the value of the comparison on success, orNULL
on failure.
You might also be interested in the PyObject_RichCompareBool
function, which does the same as PyObject_RichCompare
but returns an integer rather than a PyObject *
. Specifically, 1
is returned for true, 0
for false, and -1
for an error.