As we already told you, you really should not rely on __del__ be called when you exit the interpreter. Two options are enough for this:
First atexit
import os import atexit class Logger(object): def on_exit(self): print "os: %s." % os logger = Logger() atexit.register(logger.on_exit)
This ensures that your registrar will be completed upon exit.
* Read a little more about your problem, since you plan that one instance is attached to the module that defines the class of instances, the context manager solution below will not work for this, since there is no way to stay in context for the entire execution of your program. You need to use atexit.register . However, from the point of view of program development, I would prefer to use the context manager to manage my resources than atexit.register , if this allows atexit.register to restructure the code.
The second way (better *) is to make your class a context manager that executes the cleanup code when exiting the context. Then your code will look like this:
import os class Logger(object): def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): print "os:",str(os) with Logger() as logger:
mgilson
source share