Common path all PyObjects take on destruction?

Carl Banks pavlovevidence at gmail.com
Fri Jan 9 22:42:42 EST 2009


On Jan 9, 6:39 pm, Ryan Stutsman <stuts... at cs.stanford.edu> wrote:
> I've added a field to all PyObjects in the interpreter which is of type
> PyObject*.  Most of the time this pointer is NULL but occassionally I
> want to track some information in there.  The problem I'm running into
> is that I can add a reference to a PyObject inside any of my PyObjects,
> but it seems that there isn't any one path that all objects follow on
> destruction so that I can later Py_DECREF that reference.
>
> Eventually most of the types seem to call PyObject_Free, but this gets
> called with void* and it seems it isn't always the case that PyObject*s
> are passed in.
>
> Where is the best place to implement something like this?  It really
> won't work to implement this in the destructor of each of the individual
> types because other types added later won't know to DECREF this field on
> destruction.
>
> Any hints would be appreciated.  Hopefully I'm just missing something
> simple.


I believe no object in CPython ever gets deleted except by the
Py_DECREF macro (Py_XDECREF and Py_CLEAR both expand Py_DECREF).  So
there is your common reference point.  Let's look at the macro, shall
we?


#define Py_DECREF(op)                                   \
        if (_Py_DEC_REFTOTAL  _Py_REF_DEBUG_COMMA       \
            --((PyObject*)(op))->ob_refcnt != 0)        \
                _Py_CHECK_REFCNT(op)                    \
        else                                            \
                _Py_Dealloc((PyObject *)(op))


So, if the reference count goes down to zero, Py_DECREF calls
_Py_Dealloc to delete the object.  _Py_Dealloc is the common point you
want.


Carl Banks



More information about the Python-list mailing list