[Python-Dev] Py_CLEAR and assigning values

Daniel Stutzbach daniel at stutzbachenterprises.com
Tue Aug 5 23:04:55 CEST 2008


On Tue, Aug 5, 2008 at 3:38 PM, Paul Pogonyshev <pogonyshev at gmx.net> wrote:

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


The Py_DECREF inside the Py_CLEAR may call arbitrary code while self->x
points to NULL.  This is OK if you write your code to recognize that self->x
may be NULL.

Without Py_CLEAR, a Py_DECREF may call arbitrary code while self->x points
to a deallocated object.  This is never OK since it's impossible to detect
that self->x is bogus.

Generally, I end up storing all the objects to be Py_DECREF'd in temporary
variables and doing the Py_DECREF's just before returning.  That way, "self"
is never in an inconsistent state.

--
Daniel Stutzbach, Ph.D.
President, Stutzbach Enterprises, LLC <http://stutzbachenterprises.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20080805/acd229b7/attachment.htm>


More information about the Python-Dev mailing list