Is there any benefit of using Py_DECREF instead of Py_XDECREF for Python C extensions?

I am working on the Python C Extension documentation to define new types and have just finished Providing more granular control over data attributes .

In this section, they modify the sample code to ensure that the first and last attributes of the Noddy structure can never be NULL , for example, by initializing empty string attributes to new and adding getters and setters that raise TypeError if the user tries to delete or otherwise set these attributes to null.

Additionally (and the point of my question), the author changes all Py_XDECREF to Py_DECREF for these attributes, stating that:

With these changes, we can guarantee that the first and last members will never be NULL, so we can remove checks for NULL values ​​in almost all cases. This means that most Py_XDECREF () calls can be converted to Py_DECREF () calls. The only place we cannot change these calls is in the deallocator, where it is likely that the initialization of these members failed in the constructor.

It seems to me that it would be safer to use Py_XDECREF , given that Py_DECREF leads to a segmentation fault if it passed a NULL value.

What is the advantage of using Py_DECREF over Py_XDECREF ?

+7
python python-c-extension python-c-api
source share
1 answer

If you know that the object cannot be NULL, the advantages of Py_DECREF over Py_XDECREF are as follows:

  • he is faster because he avoids unnecessary test and jumps;
  • In addition, it ensures that it is in fact a statement with zero value, that the pointer is not NULL - the program will immediately work if the invariant is broken.

Both points can be important when working with low-level code, so the Python kernel and most extensions try to use Py_XDECREF (or Py_CLEAR ) when the pointer can actually be NULL.

+5
source share

All Articles