Python: How to (not) keep a COM-object persistent in memory after closing the parent application?
Question: i am working on a (pretty big) Python/Tkinter-application (Python 2.7 under
Windows 7) which (among many other things) calls Matlab via the COM-interface.
The basic structure of the Matlab/COM-part is like this:

    
    
    import Tkinter
    import pythoncom
    import win32com.client
    
    class App( object ):
    
        def __init__( self, parent ):
            Tkinter.Button( root, text="Start Matlab", command=self.start_matlab ).grid()
    
        def start_matlab( self ):
            self.matlab = win32com.client.Dispatch( "Matlab.Application" )
    
    root = Tkinter.Tk()
    App( root )
    root.mainloop()
    

The behaviour i observe with this simplified code is: Running the application
and clicking the button creates a Matlab-Instance (opens a Matlab-Command
window), and when closing the Tkinter application also that Matlab-window and
the corresponding entry in the Task-Manager disappear. Repeating the
procedure, Matlab is started afresh. However, when i do "the same" with my
"real" application, the Matlab instance persists after closing my application
and, moreover, when i restart the application and run the part which "starts"
Matlab, it just retrieves and uses the instance which remained in memory after
quitting the first sessiong of my app. Unfortunately, i am not able to isolate
a reasonably small code example showing the latter behavior:(

Does anybody have an idea what the reason for this is/could be?

How can one control whether a COM-object is killed or persists in memory when
the parent Python application which created it is closed?


Answer: Here's how to explicitly remove the COM object, using Tkinter's protocol
handler:

    
    
    import Tkinter
    import pythoncom
    import win32com.client
    
    class App( object ):
    
        def __init__( self, parent ):
            self.parent = parent #reference to root
            Tkinter.Button( root, text="Start Matlab", command=self.start_matlab ).grid()
            self.parent.protocol('WM_DELETE_WINDOW', self.closeAll) #protocol method
    
        def start_matlab( self ):
            self.matlab = win32com.client.Dispatch( "Matlab.Application" )
    
        def closeAll(self):
            del self.matlab       #delete the COM object
            self.parent.destroy() #close the window
    
    root = Tkinter.Tk()
    App( root )
    root.mainloop()
    

Reference: [Removing COM object from
memory](https://mail.python.org/pipermail/python-
win32/2008-February/007018.html)

[More on protocols](http://effbot.org/tkinterbook/tkinter-events-and-
bindings.htm)

