Search code examples
pythonc++python-c-apipython-c-extension

Python C API Boolean Objects


I am using Python C API 2.7.2 with my C++ console application. There is one doubt regarding Python C API Boolean Objects

I am using:

PyObject* myVariable = Py_True;

Do I need to deference myVariable with Py_DECREF(myVariable)?

The Python C API documentation says:-

The Python True object. This object has no methods. It needs to be treated just like any other object with respect to reference counts.

I searched the questions but could not find a clear answer for it.

Thanks.


Solution

  • It needs to be treated just like any other object with respect to reference counts.

    This means that you must incref it when you take its reference

    {
      Py_INCREF(Py_True);
      PyObject* myVariable = Py_True;
    

    and you must decref it when you dispose of it.

      Py_DECREF(myVariable);
    }