module finalizer - is there such a beast?

H

Helmut Jarausch

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
 
P

Peter Otten

Helmut said:
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.exiting nirvana
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top