Nicolas V
Nicolas V

Reputation: 63

Python C extension using the Limited API: how to get the value of __debug__?

I'm coding a C extension for Python.

I used the non-limited API and recently switched to Python's limited API. And with that new API, I can't see a way to get the value of the global __debug__ variable.

Previously I used the Py_OptimizeFlag variable but that variable is not available within the limited API. (And is deprecated in Python 3.12, so we won't see ever see it in the limited API anyway).

Does anyone have a solution for that?

I tried many, many solutions. Couldn't find anything useful in the doc by myself and Google didn't helped.

Upvotes: 2

Views: 44

Answers (1)

DavidW
DavidW

Reputation: 30931

__debug__ is available in __builtins__. So you can do

PyObject *builtins, *debug_str, *debug;
int flag;

builtins = PyEval_GetBuiltins();
if (!builtins) goto bad;
debug_str = PyUnicode_FromStringAndSize("__debug__", 9);
if (!debug_str) goto bad;
debug = PyObject_GetItem(builtins, debug_str);
Py_DECREF(debug_str);
if (!debug) goto bad;
flag = PyObject_IsTrue(debug);
Py_DECREF(debug);

bad: // decide how to behave in case of errors

At the end of this flag indicates whether __debug__ is true or false. You may want to cache this result for speed.

(This code is copied from Cython's implementation but it should be a pretty general way of solving this problem.)

Upvotes: 1

Related Questions