I’ve found something very strange. See this short code below.
import os
class Logger(object):
def __init__(self):
self.pid = os.getpid()
print "os: %s." %os
def __del__(self):
print "os: %s." %os
def temp_test_path():
return "./[%d].log" %(os.getpid())
logger = Logger()
This is intended for illustrative purposes. It just prints the imported module os, on the construstion and destruction of a class (never mind the name Logger). However, when I run this, the module os seems to “disappear” to None in the class destructor. The following is the output.
os: <module 'os' from 'C:\Python27\lib\os.pyc'>.
os: None.
Where is said os: None. is my problem. It should be identical to the first output line. However, look back at the python code above, at the function temp_test_path(). If I alter the name of this function slightly, to say temp_test_pat(), and keep all of the rest of the code exactly the same, and run it, I get the expected output (below).
os: <module 'os' from 'C:\Python27\lib\os.pyc'>.
os: <module 'os' from 'C:\Python27\lib\os.pyc'>.
I can’t find any explanation for this except that it’s a bug. Can you? By the way I’m using Windows 7 64 bit.
If you are relying on the interpreter shutdown to call your
__del__it could very well be that theosmodule has already been deleted before your__del__gets called. Try explicitly doing adel loggerin your code and sleep for a bit. This should show it clearly that the code functions as you expect.I also want to link you to this note in the official documentation that
__del__is not guaranteed to be called in the CPython implementation.