[Python-Dev] Py_CLEAR and assigning values

Paul Pogonyshev pogonyshev at gmx.net
Tue Aug 5 23:30:49 CEST 2008

Daniel Stutzbach wrote:
> 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.

Yes, this is quite similar to Python code

	del obj.x
	obj.x = y

though I'm not sure if for Python code x.__del__ will see obj.x as
non-set attribute (I guess so, but I'm not sure).

However, I'm trying to emulate

	obj.x = y

in C.

> 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.

Yes, this I don't argue.

> 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.

Right.  But wouldn't it be easier if there was a standard Python macro
for this, sort of like proposed Py_ASSIGN?


More information about the Python-Dev mailing list