views:

109

answers:

1

I have a python module written in C, and I would like to add a function that is called when the module is unloaded. I obviously have an initfoo function to initialize the module -- is there a way to tell python to call a finifoo function when it's uninitializing the module?

Is atexit my only option?

+4  A: 

Not in Python 2, but Python 3 seems to. If you need to manage some resource, I would advise putting it in a module-level object -- I'm pretty sure those will be garbage-collected when the module is unloaded.


From the link:

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 suggests that you could set a static boolean in your initializer that gets flipped on every call. Check it status to see whether or not the module is being finalized.

John Millikin