471,310 Members | 1,156 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,310 software developers and data experts.

module finalizer - is there such a beast?

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
Jan 11 '08 #1
2 998
You can execute cleanup code if the interpreter exits:

http://docs.python.org/lib/module-atexit.html

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...
Jan 11 '08 #2
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
Jan 11 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Ravi | last post: by
5 posts views Thread by jim | last post: by
8 posts views Thread by Richard Arthur | last post: by
21 posts views Thread by ajbecker | last post: by
5 posts views Thread by tstephan | last post: by
6 posts views Thread by Sharon | last post: by
32 posts views Thread by Matias Jansson | last post: by
3 posts views Thread by =?Utf-8?B?VHJlY2l1cw==?= | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.