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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.