module finalizer - is there such a beast?

Peter Otten __peter__ at web.de
Fri Jan 11 07:22:18 EST 2008


Helmut Jarausch wrote:

> But how can I get control when the module gets unloaded
> either by Python's gc, Python's exit or by a module reload.

Here's a simple approach using the finalizer of an object in the module's
globals():

$ cat nirvana.py
class Exit(object):
    def __del__(self):
        print "exiting", __name__

exit_watch = Exit()
$ python
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35) 
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import nirvana
>>> reload(nirvana)
exiting nirvana
<module 'nirvana' from 'nirvana.pyc'>
>>> 
exiting None
$

But don't trust it too much and don't try to access other global objects.
These may already be set to None as demonstrated above.

Peter



More information about the Python-list mailing list