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

Jim Fulton jim@zope.com
Fri, 16 May 2003 16:22:53 -0400


Tim Peters wrote:
> [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).

Hm, I didn't read the PEP, I just went by what Guido told me. :)

I was told that PyType_Ready fills in tp_alloc and tp_free with default values.

I updated the noddy example in the docs. In this example, I filled
in neither tp_alloc or tp_free.  I tested the examples and verified that
they work.

I just added printf calls to verify that these slots are indeen null before the
call to PyType_Ready and non-null afterwards.

Jim

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