diff -r acd31653e3b4 Doc/c-api/gcsupport.rst --- a/Doc/c-api/gcsupport.rst Thu Jan 16 06:53:54 2014 +0100 +++ b/Doc/c-api/gcsupport.rst Thu Jan 16 14:48:37 2014 +0100 @@ -150,3 +150,34 @@ this method (don't just call :c:func:`Py_DECREF` on a reference). The collector will call this method if it detects that this object is involved in a reference cycle. + +Practical Considerations +------------------------ + +From the perspective of an extension writer, correctly implementing support for +cyclic garbage collection is easier than it appears from the above description. +If no custom :c:member:`~PyTypeObject.tp_alloc` and +:c:member:`~PyTypeObject.tp_free` functions are specified, the default handlers +will adhere to the GC rules for constructors and deallocators. +In that case, specifying the :const:`Py_TPFLAGS_HAVE_GC` flag, and implementing +the :c:member:`~PyTypeObject.tp_traverse` and +:c:member:`~PyTypeObject.tp_clear` handlers is enough to fully support cyclic +garbage collection. Most extension writers will never need to worry about +:c:func:`PyObject_GC_Track` and :c:func:`PyObject_GC_UnTrack` or how memory is +allocated. + +In contrast, container types supporting cyclic garbage collection while +implementing custom memory management require special thought. +The rule for memory to be allocated with :c:func:`PyObject_GC_New` or +:c:func:`PyObject_GC_NewVar` prevents the use of other memory allocation +backends. Placing several Python objects in a larger memory pool previously +allocated via :c:func:`PyObject_GC_New` is not supported either. Consequently, +custom allocators can in practice only rely on :c:func:`PyObject_GC_New` or +:c:func:`PyObject_GC_NewVar`, while taking care to call +:c:func:`PyObject_GC_Track` before returning. + +If truly custom memory allocation is required for extension classes, the +:const:`Py_TPFLAGS_HAVE_GC` flag must be omitted. The resulting objects will +still be destroyed as long as they are not part of any reference cycle. +Possible ways to meet this requirement are to not hold references to other +Python objects or to judiciously use weak references.