Friday, June 08, 2007
Python destructors and sys.exit()
I'm hastily writing a object-oriented GUI app in Python 2.5 that logs keystrokes to a remote textfile. As such, I create Python's file handler object (file/open) in my class's constructor and keep it resident throughout the life of the app to properly handle keypress events. But wanting to be a good memory patron, I'm calling file.close() in the destructor, which technically is after a user could terminate the app by clicking an Exit button I'm handling via sys.exit().
I'm wondering if I might be introducing memory leaks or not managing open objects as well as I could, and possibly introducing dangling references. Consider the following:
I'm wondering if I might be introducing memory leaks or not managing open objects as well as I could, and possibly introducing dangling references. Consider the following:
def __init__(self):
self.file = open('foobar.log','a')
def __del__(self):
self.file.close()
def capture_password(self,event): #handles event logging
print >> self.file,('Password:%s' % (event.char))
def terminate(self): # handles a 'Quit' button click
sys.exit()
Comments:
Links to this post:
<< Home
Or maybe I can play defensive and just call the destructor method from within the terminate() method. Hmm...
Use the with statement, which is like the using statement in C#. Makes sure all the garbage is collected when you go out of scope. Maybe?
I did think about that, but I'm not so sure I can use that in my current code because the call to close() is outside of the scope of the block. Maybe if I refactor...
Links to this post:
<< Home
Subscribe to Posts [Atom]

Post a Comment