5

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.

Nacib Neme
  • 859
  • 1
  • 17
  • 28

1 Answers1

12

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 and o2 using the operation specified by opid, which must be one of Py_LT, Py_LE, Py_EQ, Py_NE, Py_GT, or Py_GE, corresponding to <, <=, ==, !=, >, or >= respectively. This is the equivalent of the Python expression o1 op o2, where op is the operator corresponding to opid. Returns the value of the comparison on success, or NULL 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.