[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

module finalizer - is there such a beast?

Helmut Jarausch

1/11/2008 8:28:00 AM

Hi,

when a module gets imported the statements not contained in
function definitions or classes are executed.
This can be thought of an initializer for the module.

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

Many thanks for a hint,

Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
2 Answers

Thomas Troeger

1/11/2008 11:48:00 AM

0

You can execute cleanup code if the interpreter exits:

http://docs.python.org/lib/module-a...

This will only cover the `Python's exit' part of your question, not the
module reloading stuff. On the other hand, if you load a module you
could set a global variable and check for it on reload...

Peter Otten

1/11/2008 12:22:00 PM

0

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