Run a function when a C extension module is freed on python 2

100 views Asked by At

I have a C extension module for Python.

When the module is initialized, I malloc() some memory that I only use in the C code.

I would like to free this memory when the module is freed.

Python 3 has m_free member on PyModuleDef struct that is exactly what I want. The problem is I cannot find equivalent functionality in Python 2.

How do I free my malloc'd memory in Python 2?

1

There are 1 answers

0
alko On BEST ANSWER

I suppose there is no direct equivalent, that's why m_free is introduced in 3.0, see pep 3121 for details:

Currently, extension modules are initialized usually once and then "live" forever. The only exception is when Py_Finalize() is called: then the initialization routine is invoked a second time. This is bad from a resource management point of view: memory and other resources might get allocated each time initialization is called, but there is no way to reclaim them. As a result, there is currently no way to completely release all resources Python has allocated.