Common path all PyObjects take on destruction?

R

Ryan Stutsman

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

Carl Banks

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,114
Latest member
GlucoPremiumReview
Top