Extending Python with C or C++ involves defining a shared library which exposes an initialization function along the lines of
PyMODINIT_FUNC
initspam(void)
{
(void) Py_InitModule("spam", SpamMethods);
}
Assuming I allocate resources here, like allocating a global object via
g_bookkeeping = new Bookkeeping;
What would be the correct place to write the corresponding delete statement? There doesn't seem to be any hook for noticing that a module is unloaded, or is there?
I briefly considered using a global object, like
Bookkeeping g_bookkeeping;
...but I'd like to have precise control over when that object is constructed or destructed.
The Python documentations talks about finalization and mentions a Py_Finalize() call which -- at least in Python 2.x -- internally calls PyImport_Cleanup. However, that doesn't seem to do much as far as customizing the module shutdown goes.
A message to an issue from 2010 states for the version of Python you're using:
[...]
Please accept that Python indeed does not support unloading modules for severe, fundamental, insurmountable, technical problems, in 2.x.
[...]
Supporting unloading will be (and was) a multi-year project. Don't expect any results in the next five years.
The documentation for Py_Finalize() also mentions as Bugs and caveats:
Dynamically loaded extension modules loaded by Python are not unloaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With