Extension module finalization?

Alex Martelli aleax at aleax.it
Tue Jan 15 09:39:58 EST 2002


"Martin Sjögren" <martin at strakt.com> wrote in message
news:mailman.1011086782.28094.python-list at python.org...
Hello

"""
When writing an extension module in C, you write an initfoo function that
initializes the module. Is there a way to get a function called when the
module is finalized? Like, if I want to do cleanup or stuff like that...
"""

I think the only "offical" way is:
http://www.python.org/doc/current/lib/module-atexit.html

as modules don't get "finalized" until Python-exit time (if I
understand correctly).


However, a long-running Python application might reload updated
modules and in that sense "finalize" the previous loaded version
without having the whole process terminate.  Is this what you
have in mind in terms of "module being finalized"?

I suspect that, to catch such cases, you might be best off
adapting my class-as-fake-module recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207

The adaptation that I have in mind is that, after the normal
initialization including Py_InitModule("foo", foomethods),
module foo would instantiate this class:

class ModuleWrapper:
    def __init__(self, modulename, call_at_end):
        import sys
        self.__module = sys.modules[modulename]
        self.__call_at_end = call_at_end
        sys.modules[modulename] = self
    def __getattr__(self, name):
        return getattr(self.__module, name)
    del __del__(self):
        self.__call_at_end()

You may add __setattr__ and __delattr__, too, but in this
case be sure to avoid triggering __setattr__ undesiredly:

    def __init__(self, modulename, call_at_end):
        import sys
        self.__dict__['_ModuleWrapper__module'] = sys.modules[modulename]

etc etc.


Another, simpler idea worth trying would be to have the
module object hold the sole reference to an object whose
__del__ calls the finalization function, rather than, as
here, vice versa.  If Python properly finalizes the module
object's exposed attributes, when it (e.g.) reloads the
module, it should then in particular remove that "sole
reference" and thus trigger its __del__.  I would think
that this approach might be more at risk of creating a
reference-loop (if the finalization function holds a
reference to the module object, for example) impeding
prompt finalization (cfr later).


I have not tried either of these approaches -- and both
rely on CPython's current "guaranteed prompt finalization
when last reference to object goes away" semantics, and
in this sense they might be fragile wrt future changes,
as it's well known that "finalization promptness" is NOT
guaranteed as a Python _language_ characteristic... it's
just a nice property of some implementations (but Jython,
for example, does not have it).


Alex






More information about the Python-list mailing list