pythoncpython-c-apipyobject

error: value of type 'PyObject' (aka '_object') is not contextually convertible to 'bool'


I am passing a python module to C as a PyObject. I want to check to see if this value is NONE in my C code, using this form:

int func(PyObject tmp)
{
   if(tmp)
    { 
     // etc

I am getting the following error. How can I convert from a PyObject to boolean value, simillar to the way Python's if function behaves. It is worth noting that when tmp is a boost::python::object variable this command works as expected.

ex_program.cpp:72:7: error: value of type 'PyObject' (aka '_object') is not contextually convertible to 'bool'
  if (tmp)
      ^~~

Solution

  • PyObject_IsTrue seems to do what you want:

    int PyObject_IsTrue(PyObject *o)
    
        Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.