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

Tim Peters tim@zope.com
Fri, 16 May 2003 15:29:54 -0400


[Jim Fulton]
> ...
> 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
> empty.

I'm worried about half of that:  tp_free is needed to release memory no
matter whether obtained in a standard or custom way.  I don't think tp_free
slots always get filled in to something non-NULL by magic, and in the
current Python source almost all new-style C types explicitly define a
tp_free function (the exceptions are "strange" in some way).

PEP 253 may be partly out of date here -- or not.  In the section on
creating a subclassable type, it says:

"""
   The base type must do the following:

      - Add the flag value Py_TPFLAGS_BASETYPE to tp_flags.

      - Declare and use tp_new(), tp_alloc() and optional tp_init()
        slots.

      - Declare and use tp_dealloc() and tp_free().

      - Export its object structure declaration.

      - Export a subtyping-aware type-checking macro.
"""

This doesn't leave a choice about defining tp_alloc() or tp_free() -- it
says both are required.  For a subclassable type, I believe both must
actually be implemented too.

For a non-subclassable type, I expect they're optional.  But if you don't
define tp_free in that case, then I believe you must also not do the

    obj->ob_type->tp_free(obj)

business in the tp_dealloc slot (else it will segfault).