The Jason Salas Experience

Guam's Mr. Media - making people think, making people laugh, pissing people off

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:

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()

3 Comments:

  • At June 8, 2007 12:34 PM, Blogger Jason Salas said…

    Or maybe I can play defensive and just call the destructor method from within the terminate() method. Hmm...

     
  • At June 11, 2007 4:37 AM, Blogger Lindsay said…

    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?

     
  • At June 11, 2007 1:51 PM, Blogger Jason Salas said…

    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...

     

Post a Comment

Links to this post:

Create a Link

<< Home