Garbage Collection Question

Michael Hudson mwh at
Fri Aug 29 14:00:35 CEST 2003

csv610 at (Chaman Singh Verma) writes:

> I am trying to integrate C++ with Python. I read that Python does
> automatic garbage collection. I am creating new objects in C++ and
> passing to Python, I don't know now who should control deleting the
> objects.

Um, I think I need more detail to fully answer this.

> If I create objects in C++ do I have to clean them or Python will
> use GC to remove unwanted objects.

As Aahz noted, Python only GCs objects it knows about, i.e. PyObjects.

A common pattern is to have a custom Python object encapsulate one of
your C++ objects.  So you do something like this:

static PyTypeObject Thing_Type;

struct ThingObject {
    Thing* thing;

PyObject* Thing_New()
    Thing* thing = PyObject_New(ThingObject, &Thing_Type);
    thing->thing = new Thing();
    return (PyObject*)thing;

void thing_dealloc(PyObject* thing)
    delete ((ThingObject*)thing)->thing;

and make sure thing_dealloc ends up in the tp_dealloc slot of


  y'rs - tim
              -- Tim Peters dishes out versioning advice on python-dev

More information about the Python-list mailing list