[Python-Dev] C new-style classes and GC

Jim Fulton jim@zope.com
Fri, 16 May 2003 11:46:19 -0400

Lately I've been re-learning how to write new types in C.  Things
changed drastically (for the better) in 2.2. I've been updating the
documentation on writing new types as I go:


(I'm also updating modulator.)

I'm starting to try to figure out how to integrate support for GC.
The current documentation in the section "Supporting the Cycle
Collector" doesn't reflect new-style types and is, thus, out of date.

Frankly, I'm taking the approach that there is only One Way to create
types in C, the new way, based on new-style types as now documented
in the manual.

I'll also note that most new-style types don't need and thus don't
implement custom allocators. They leave the tp_alloc and tp_free slots

So given that we have a new style type, to add support for GC, we need

- Set the Py_TPFLAGS_HAVE_GC type flag,

- Provide implementations of tp_traverse and tp_clear, as described in
   the section "Supporting the Cycle Collector" section of the docs.

- Call PyObject_GC_UnTrack at the beginning of the deallocator,
   before decrefing any members.

I think that that is *all* we have to do.

In particular, since we have a new style type that inherits the
standard allocator, we don't need to fool with PyObject_GC_New, and
PyObject_GC_DEL, because the default tp_alloc and tp_free take care of
that for us. Similarly, we don't need to call PyObject_GC_Track,
because that is done by the default allocator. (Because of that, our
traverse function has to check for null object pointers in our
object's members.)

Did I get this right? I intend to update the docs to reflect this
understanding (or a corrected one, of course).


Jim Fulton           mailto:jim@zope.com       Python Powered!
CTO                  (703) 361-1714            http://www.python.org
Zope Corporation     http://www.zope.com       http://www.zope.org