1

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.

D3XT3R
  • 181
  • 2
  • 15

2 Answers2

3

Although it isn't dynamically created, it must be reference counted because PyObject variables can hold ANY Python object. Otherwise there would need to be checks for Py_True and other special cases scattered throughout the Python runtime as well as any C/C++ code that uses the API. That would be messy and error prone.

Mike Collins
  • 402
  • 3
  • 13
2

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);
}
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358