Hello,
In a PoC I’m working on, I’d like to use the Py_mod_create
slot in a PyModuleDef
to return a module that’s of a custom type, subclassing PyModule_Type
. A value of this type can, then, contain extra data that can then be used by Py_mod_exec
, m_free
and similar functions, whilst retaining special-cased support for PyModule_Type
modules in the import machinery.
I started implementing this type as a heap-allocated type (trying to target the limited API), using a static PyType_Spec
. Since the object structure of moduletype
isn’t public, I use a negative basicsize
in the spec. Finally, I use PyType_FromSpecWithBases(&spec, (PyObject *)&PyModule_Type)
to instantiate the type object.
This works, but I’m puzzled about implementing the Py_tp_dealloc
slot for my type, for two reasons, both related to the fact I need to (also) call PyModule_Type->tp_dealloc
from my custom tp_dealloc
function (unless I’m mistaken and this wouldn’t be required?!):
-
module_dealloc
callsPyObject_GC_UnTrack
. I didn’t setPy_TPFLAGS_HAVE_GC
in my customPyType_Spec
, but maybe that’s be required given the base type has it? If I need the flag, I should also callPyObject_GC_UnTrack
before doing anything else in mytp_dealloc
hook (including before callingPyModule_Type->tp_dealloc
). Would it be an issue if the function gets called twice, then? The docs aren’t conclusive about this. -
Given this is a heap type, I have to
Py_DECREF
the type of an instance intp_dealloc
. CurrentlyPyModule_Type
is not a heap type, so I should not expect it to do so, but in some later implementation it might be transformed into a heap type, and then I should not decref the object’s type intp_dealloc
(otherwise the type gets decref’ed twice). What’s a common pattern to be “future-proof” here? Should I check the flags ofPyModule_Type
for thePy_TPFLAGS_HEAP
type, and if it is, assume it’ll perform the decref for me?
Thanks in advance!