Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I define code to release resources allocated in a C Python module init function?

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.

like image 544
Frerich Raabe Avatar asked Apr 29 '26 13:04

Frerich Raabe


1 Answers

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.

like image 129
tynn Avatar answered May 02 '26 03:05

tynn