[Python-Dev] Proposal: C API Macro to decref and set to NULL

Jim Fulton jim at zope.com
Mon Jul 12 23:21:31 CEST 2004


Often, in C type implementations, you want to set a PyObject * slot
to NULL.  Often this goes like:

   Py_XDECREF(self->foo);
   self->foo = NULL;

However, if your type participates in GC and self->foo is something that
might get traversed, this can lead to traversing self->foo after it has been
DECREFed, but before it's set to NULL.

The correct way to do this is something like:

   tmp = self->foo;
   self->foo = NULL;
   Py_XDECREF(tmp);

I suggest that there should be a standard macro to automate this.

   Py_CLEAR(self->foo)

This would be defined to be the same result as Py_XDECREF except
that the argument will be set to NULL.

Thoughts?

If there are no objections I'll add the following definition to object.h,
after the definition for Py_DECREF:

#define Py_CLEAR(op)				\
         do {                            	\
                 if (op) {			\
                         PyObject *tmp = (op);	\
                         (op) = NULL;		\
                         Py_DECREF(tmp);		\
                 }				\
         } while (0)

and update the docs and the tutorial on creating types in C.

Jim

-- 
Jim Fulton           mailto:jim at zope.com       Python Powered!
CTO                  (540) 361-1714            http://www.python.org
Zope Corporation     http://www.zope.com       http://www.zope.org


More information about the Python-Dev mailing list