[Python-Dev] Py_CLEAR and assigning values

Paul Pogonyshev pogonyshev at gmx.net
Tue Aug 5 22:38:21 CEST 2008


Sorry if this topic was discussed before, but I couldn't find.

Py_CLEAR documentation explains why it is better than Py_DECREF and
NULL assignment.  However, I don't understand why there is no similar
macro for the case you want to replace one object with another?

I.e. 'naive' way:

	Py_DECREF (self->x);
        /* This is prone to the same bug Py_CLEAR prevents. */
	self->x = y;
	Py_INCREF (self->x);

Py_CLEAR way:

	Py_CLEAR (self->x);
        /* But __del__ can now in principle trigger access to NULL. */
	self->x = y;
	Py_INCREF (self->x);

Way I'd think would be possible:

	Py_ASSIGN (self->x, y)

where Py_ASSIGN is defined this way:

#define Py_ASSIGN(op, val)				\
        do {						\
		PyObject *_py_tmp = (PyObject *)(op);	\
		(op) = val;				\
		Py_XINCREF(op);				\
		Py_XDECREF(_py_tmp);			\
        } while (0)

Do I miss something obvious?  Or is there already a standard way to
do that which I overlooked?


More information about the Python-Dev mailing list