D3XT3R
D3XT3R

Reputation: 171

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.

Upvotes: 1

Views: 1229

Answers (2)

Mike Collins
Mike Collins

Reputation: 452

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.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798746

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);
}

Upvotes: 2

Related Questions